The Battle for Wesnoth  1.15.3+dev
lua_kernel_base.cpp
Go to the documentation of this file.
1 /*
2  Copyright (C) 2014 - 2018 by Chris Beck <render787@gmail.com>
3  Part of the Battle for Wesnoth Project https://www.wesnoth.org/
4 
5  This program is free software; you can redistribute it and/or modify
6  it under the terms of the GNU General Public License as published by
7  the Free Software Foundation; either version 2 of the License, or
8  (at your option) any later version.
9  This program is distributed in the hope that it will be useful,
10  but WITHOUT ANY WARRANTY.
11 
12  See the COPYING file for more details.
13 */
14 
16 
17 #include "game_config.hpp"
18 #include "game_errors.hpp"
19 #include "gui/core/gui_definition.hpp" // for remove_single_widget_definition
20 #include "log.hpp"
21 #include "lua_jailbreak_exception.hpp" // for lua_jailbreak_exception
22 #include "random.hpp"
23 #include "seed_rng.hpp"
24 #include "deprecation.hpp"
25 #include "language.hpp" // for get_language
26 
27 #ifdef DEBUG_LUA
28 #include "scripting/debug_lua.hpp"
29 #endif
30 
31 #include "scripting/lua_color.hpp"
32 #include "scripting/lua_common.hpp"
36 #include "scripting/lua_gui2.hpp"
37 #include "scripting/lua_wml.hpp"
40 #include "scripting/lua_rng.hpp"
41 #include "scripting/push_check.hpp"
42 
43 #include "game_version.hpp" // for do_version_check, etc
44 #include "picture.hpp"
45 
46 #include "utils/functional.hpp"
47 #include "utils/name_generator.hpp"
50 
51 #include <cstring>
52 #include <exception>
53 #include <new>
54 #include <string>
55 #include <sstream>
56 #include <vector>
57 
58 #include "lua/lauxlib.h"
59 #include "lua/lua.h"
60 #include "lua/lualib.h"
61 
62 static lg::log_domain log_scripting_lua("scripting/lua");
63 static lg::log_domain log_user("scripting/lua/user");
64 #define DBG_LUA LOG_STREAM(debug, log_scripting_lua)
65 #define LOG_LUA LOG_STREAM(info, log_scripting_lua)
66 #define WRN_LUA LOG_STREAM(warn, log_scripting_lua)
67 #define ERR_LUA LOG_STREAM(err, log_scripting_lua)
68 
69 // Registry key for metatable
70 static const char * Gen = "name generator";
71 // Registry key for lua interpreter environment
72 static const char * Interp = "lua interpreter";
73 
74 // Callback implementations
75 
76 /**
77  * Compares 2 version strings - which is newer.
78  * - Args 1,3: version strings
79  * - Arg 2: comparison operator (string)
80  * - Ret 1: comparison result
81  */
83 {
84  char const *v1 = luaL_checkstring(L, 1);
85 
87  if(vop == OP_INVALID) return luaL_argerror(L, 2, "unknown version comparison operator - allowed are ==, !=, <, <=, > and >=");
88 
89  char const *v2 = luaL_checkstring(L, 3);
90 
91  const bool result = do_version_check(version_info(v1), vop, version_info(v2));
92  lua_pushboolean(L, result);
93 
94  return 1;
95 }
96 
97 /**
98  * Replacement print function -- instead of printing to std::cout, print to the command log.
99  * Intended to be bound to this' command_log at registration time.
100  */
102 {
103  DBG_LUA << "intf_print called:\n";
104  std::size_t nargs = lua_gettop(L);
105 
106  lua_getglobal(L, "tostring");
107  for (std::size_t i = 1; i <= nargs; ++i) {
108  lua_pushvalue(L, -1); // function to call: "tostring"
109  lua_pushvalue(L, i); // value to pass through tostring() before printing
110  lua_call(L, 1, 1);
111  const char * str = lua_tostring(L, -1);
112  if (!str) {
113  LOG_LUA << "'tostring' must return a value to 'print'\n";
114  str = "";
115  }
116  if (i > 1) {
117  cmd_log_ << "\t"; //separate multiple args with tab character
118  }
119  cmd_log_ << str;
120  DBG_LUA << "'" << str << "'\n";
121  lua_pop(L, 1); // Pop the output of tostrring()
122  }
123  lua_pop(L, 1); // Pop 'tostring' global
124 
125  cmd_log_ << "\n";
126  DBG_LUA << "\n";
127 
128  return 0;
129 }
130 
131 /**
132  * Replacement load function. Mostly the same as regular load, but disallows loading binary chunks
133  * due to CVE-2018-1999023.
134  */
135 static int intf_load(lua_State* L)
136 {
137  std::string chunk = luaL_checkstring(L, 1);
138  const char* name = luaL_optstring(L, 2, chunk.c_str());
139  std::string mode = luaL_optstring(L, 3, "t");
140  bool override_env = !lua_isnone(L, 4);
141 
142  if(mode != "t") {
143  return luaL_argerror(L, 3, "binary chunks are not allowed for security reasons");
144  }
145 
146  int result = luaL_loadbufferx(L, chunk.data(), chunk.length(), name, "t");
147  if(result != LUA_OK) {
148  lua_pushnil(L);
149  // Move the nil as the first return value, like Lua's own load() does.
150  lua_insert(L, -2);
151 
152  return 2;
153  }
154 
155  if(override_env) {
156  // Copy "env" to the top of the stack.
157  lua_pushvalue(L, 4);
158  // Set "env" as the first upvalue.
159  const char* upvalue_name = lua_setupvalue(L, -2, 1);
160  if(upvalue_name == nullptr) {
161  // lua_setupvalue() didn't remove the copy of "env" from the stack, so we need to do it ourselves.
162  lua_pop(L, 1);
163  }
164  }
165 
166  return 1;
167 }
168 
169 // The show lua console callback is similarly a method of lua kernel
171 {
172  if (cmd_log_.external_log_) {
173  std::string message = "There is already an external logger attached to this lua kernel, you cannot open the lua console right now.";
174  log_error(message.c_str());
175  cmd_log_ << message << "\n";
176  return 0;
177  }
178 
179  return lua_gui2::show_lua_console(L, this);
180 }
181 
183 {
184  name_generator* gen = static_cast<name_generator*>(lua_touserdata(L, 1));
185  lua_pushstring(L, gen->generate().c_str());
186  return 1;
187 }
188 
190 {
191  name_generator* gen = static_cast<name_generator*>(lua_touserdata(L, 1));
192  gen->~name_generator();
193  return 0;
194 }
195 
197 {
198  std::string type = luaL_checkstring(L, 1);
199  name_generator* gen = nullptr;
200  try {
201  if(type == "markov" || type == "markov_chain") {
202  std::vector<std::string> input;
203  if(lua_istable(L, 2)) {
204  input = lua_check<std::vector<std::string>>(L, 2);
205  } else {
206  input = utils::parenthetical_split(luaL_checkstring(L, 2), ',');
207  }
208  int chain_sz = luaL_optinteger(L, 3, 2);
209  int max_len = luaL_optinteger(L, 4, 12);
210  gen = new(L) markov_generator(input, chain_sz, max_len);
211  // Ensure the pointer didn't change when cast
212  assert(static_cast<void*>(gen) == dynamic_cast<markov_generator*>(gen));
213  } else if(type == "context_free" || type == "cfg" || type == "CFG") {
214  if(lua_istable(L, 2)) {
215  std::map<std::string, std::vector<std::string>> data;
216  for(lua_pushnil(L); lua_next(L, 2); lua_pop(L, 1)) {
217  if(lua_type(L, -2) != LUA_TSTRING) {
218  lua_pushstring(L, "CFG generator: invalid nonterminal name (must be a string)");
219  return lua_error(L);
220  }
221  if(lua_isstring(L, -1)) {
222  data[lua_tostring(L,-2)] = utils::split(lua_tostring(L,-1),'|');
223  } else if(lua_istable(L, -1)) {
224  data[lua_tostring(L,-2)] = lua_check<std::vector<std::string>>(L, -1);
225  } else {
226  lua_pushstring(L, "CFG generator: invalid noterminal value (must be a string or list of strings)");
227  return lua_error(L);
228  }
229  }
230  if(!data.empty()) {
231  gen = new(L) context_free_grammar_generator(data);
232  }
233  } else {
235  }
236  if(gen) {
237  assert(static_cast<void*>(gen) == dynamic_cast<context_free_grammar_generator*>(gen));
238  }
239  } else {
240  return luaL_argerror(L, 1, "should be either 'markov_chain' or 'context_free'");
241  }
242  }
243  catch (const name_generator_invalid_exception& ex) {
244  lua_pushstring(L, ex.what());
245  return lua_error(L);
246  }
247 
248  // We set the metatable now, even if the generator is invalid, so that it
249  // will be properly collected if it was invalid.
251  lua_setmetatable(L, -2);
252 
253  return 1;
254 }
255 
256 /**
257 * Returns a random numer, same interface as math.random.
258 */
259 static int intf_random(lua_State *L)
260 {
261  if (lua_isnoneornil(L, 1)) {
262  double r = static_cast<double>(randomness::generator->next_random());
263  double r_max = static_cast<double>(std::numeric_limits<uint32_t>::max());
264  lua_push(L, r / (r_max + 1));
265  return 1;
266  }
267  else {
268  int32_t min;
269  int32_t max;
270  if (lua_isnumber(L, 2)) {
271  min = lua_check<int32_t>(L, 1);
272  max = lua_check<int32_t>(L, 2);
273  }
274  else {
275  min = 1;
276  max = lua_check<int32_t>(L, 1);
277  }
278  if (min > max) {
279  return luaL_argerror(L, 1, "min > max");
280  }
281  lua_push(L, randomness::generator->get_random_int(min, max));
282  return 1;
283  }
284 }
285 
286 /**
287 * Logs a message
288 * Arg 1: (optional) Logger
289 * Arg 2: Message
290 */
291 static int intf_log(lua_State *L) {
292  const std::string& logger = lua_isstring(L, 2) ? luaL_checkstring(L, 1) : "";
293  std::string msg = lua_isstring(L, 2) ? luaL_checkstring(L, 2) : luaL_checkstring(L, 1);
294  if(msg.empty() || msg.back() != '\n') {
295  msg += '\n';
296  }
297 
298  if(logger == "err" || logger == "error") {
299  LOG_STREAM(err, log_user) << msg;
300  } else if(logger == "warn" || logger == "wrn" || logger == "warning") {
302  } else if((logger == "debug" || logger == "dbg")) {
304  } else {
306  }
307  return 0;
308 }
309 
310 /**
311  * Logs a deprecation message. See deprecation.cpp for details
312  * Arg 1: Element to be deprecated.
313  * Arg 2: Deprecation level.
314  * Arg 3: Version when element may be removed.
315  * Arg 4: Additional detail message.
316  */
318  const std::string elem = luaL_checkstring(L, 1);
319  // This could produce an invalid deprecation level, but that possibility is handled in deprecated_message()
321  const std::string ver_str = lua_isnoneornil(L, 3) ? "" : luaL_checkstring(L, 3);
322  const std::string detail = luaW_checktstring(L, 4);
323  const version_info ver = ver_str.empty() ? game_config::wesnoth_version.str() : ver_str;
324  const std::string msg = deprecated_message(elem, level, ver, detail);
325  if(level < DEP_LEVEL::INDEFINITE || level >= DEP_LEVEL::REMOVED) {
326  // Invalid deprecation level or level 4 deprecation should raise an interpreter error
327  lua_push(L, msg);
328  return lua_error(L);
329  }
330  return 0;
331 }
332 
333 /**
334 * Gets the dimension of an image.
335 * - Arg 1: string.
336 * - Ret 1: width.
337 * - Ret 2: height.
338 */
340  char const *m = luaL_checkstring(L, 1);
341  image::locator img(m);
342  if(!img.file_exists()) return 0;
343  surface s = get_image(img);
344  lua_pushinteger(L, s->w);
345  lua_pushinteger(L, s->h);
346  return 2;
347 }
348 
349 /**
350 * Returns the time stamp, exactly as [set_variable] time=stamp does.
351 * - Ret 1: integer
352 */
354  lua_pushinteger(L, SDL_GetTicks());
355  return 1;
356 }
357 
359 {
360  lua_push(L, get_language().localename);
361  return 1;
362 }
363 
364 // End Callback implementations
365 
366 // Template which allows to push member functions to the lua kernel base into lua as C functions, using a shim
368 
369 template <member_callback method>
371  return ((lua_kernel_base::get_lua_kernel<lua_kernel_base>(L)).*method)(L);
372 }
373 
374 // Ctor, initialization
376  : mState(luaL_newstate())
377  , cmd_log_()
378 {
380  lua_State *L = mState;
381 
382  cmd_log_ << "Initializing " << my_name() << "...\n";
383 
384  // Define the CPP_function metatable ( so we can override print to point to a C++ member function, add "show_dialog" for this kernel, etc. )
385  // Do it first of all in case C++ functions are ever used in the core Wesnoth libs loaded in the next step
386  cmd_log_ << "Adding boost function proxy...\n";
387 
389 
390  // Open safe libraries.
391  // Debug and OS are not, but most of their functions will be disabled below.
392  cmd_log_ << "Adding standard libs...\n";
393 
394  static const luaL_Reg safe_libs[] {
395  { "", luaopen_base },
396  { "table", luaopen_table },
397  { "string", luaopen_string },
398  { "math", luaopen_math },
399  { "coroutine", luaopen_coroutine },
400  { "debug", luaopen_debug },
401  { "os", luaopen_os },
402  { "utf8", luaopen_utf8 }, // added in Lua 5.3
403  // Wesnoth libraries
404  { "stringx",lua_stringx::luaW_open },
405  { "wml", lua_wml::luaW_open },
406  { "gui", lua_gui2::luaW_open },
407  { nullptr, nullptr }
408  };
409  for (luaL_Reg const *lib = safe_libs; lib->func; ++lib)
410  {
411  luaL_requiref(L, lib->name, lib->func, true);
412  lua_pop(L, 1); /* remove lib */
413  }
414 
415  // Disable functions from os which we don't want.
416  lua_getglobal(L, "os");
417  lua_pushnil(L);
418  while(lua_next(L, -2) != 0) {
419  lua_pop(L, 1);
420  char const* function = lua_tostring(L, -1);
421  if(strcmp(function, "clock") == 0 || strcmp(function, "date") == 0
422  || strcmp(function, "time") == 0 || strcmp(function, "difftime") == 0) continue;
423  lua_pushnil(L);
424  lua_setfield(L, -3, function);
425  }
426  lua_pop(L, 1);
427 
428  // Delete dofile and loadfile.
429  lua_pushnil(L);
430  lua_setglobal(L, "dofile");
431  lua_pushnil(L);
432  lua_setglobal(L, "loadfile");
433 
434  // Store the error handler.
435  cmd_log_ << "Adding error handler...\n";
437 
438 
439  lua_settop(L, 0);
440 
441  // Add some callback from the wesnoth lib
442  cmd_log_ << "Registering basic wesnoth API...\n";
443 
444  static luaL_Reg const callbacks[] {
445  { "compare_versions", &intf_compare_versions },
446  { "deprecated_message", &intf_deprecated_message },
447  { "have_file", &lua_fileops::intf_have_file },
448  { "read_file", &lua_fileops::intf_read_file },
449  { "canonical_path", &lua_fileops::intf_canonical_path },
450  { "textdomain", &lua_common::intf_textdomain },
451  { "get_dialog_value", &lua_gui2::intf_get_dialog_value },
452  { "set_dialog_tooltip", &lua_gui2::intf_set_dialog_tooltip },
453  { "set_dialog_active", &lua_gui2::intf_set_dialog_active },
454  { "set_dialog_visible", &lua_gui2::intf_set_dialog_visible },
455  { "add_dialog_tree_node", &lua_gui2::intf_add_dialog_tree_node },
456  { "set_dialog_callback", &lua_gui2::intf_set_dialog_callback },
457  { "set_dialog_canvas", &lua_gui2::intf_set_dialog_canvas },
458  { "set_dialog_focus", &lua_gui2::intf_set_dialog_focus },
459  { "set_dialog_markup", &lua_gui2::intf_set_dialog_markup },
460  { "set_dialog_value", &lua_gui2::intf_set_dialog_value },
461  { "remove_dialog_item", &lua_gui2::intf_remove_dialog_item },
462  { "dofile", &dispatch<&lua_kernel_base::intf_dofile> },
463  { "require", &dispatch<&lua_kernel_base::intf_require> },
464  { "kernel_type", &dispatch<&lua_kernel_base::intf_kernel_type> },
465  { "show_dialog", &lua_gui2::show_dialog },
466  { "compile_formula", &lua_formula_bridge::intf_compile_formula},
467  { "eval_formula", &lua_formula_bridge::intf_eval_formula},
468  { "name_generator", &intf_name_generator },
469  { "random", &intf_random },
470  { "log", &intf_log },
471  { "get_image_size", &intf_get_image_size },
472  { "get_time_stamp", &intf_get_time_stamp },
473  { "get_language", &intf_get_language },
474  { nullptr, nullptr }
475  };
476 
477  lua_getglobal(L, "wesnoth");
478  if (!lua_istable(L,-1)) {
479  lua_newtable(L);
480  }
481  luaL_setfuncs(L, callbacks, 0);
482  //lua_cpp::set_functions(L, cpp_callbacks, 0);
483  lua_setglobal(L, "wesnoth");
484 
485  // Create the gettext metatable.
487  // Create the tstring metatable.
489 
490  // Override the print function
491  cmd_log_ << "Redirecting print function...\n";
492 
493  lua_getglobal(L, "print");
494  lua_setglobal(L, "std_print"); //storing original impl as 'std_print'
495  lua_settop(L, 0); //clear stack, just to be sure
496 
497  lua_pushcfunction(L, &dispatch<&lua_kernel_base::intf_print>);
498  lua_setglobal(L, "print");
499 
501  lua_setglobal(L, "load");
502  lua_pushnil(L);
503  lua_setglobal(L, "loadstring");
504 
505  cmd_log_ << "Initializing package repository...\n";
506  // Create the package table.
507  lua_getglobal(L, "wesnoth");
508  lua_newtable(L);
509  lua_setfield(L, -2, "package");
510  lua_pop(L, 1);
511  lua_settop(L, 0);
512  lua_pushstring(L, "lua/package.lua");
513  int res = intf_require(L);
514  if(res != 1) {
515  cmd_log_ << "Error: Failed to initialize package repository. Falling back to less flexible C++ implementation.\n";
516  }
517 
518  // Get some callbacks for map locations
519  cmd_log_ << "Adding map table...\n";
520 
521  static luaL_Reg const map_callbacks[] {
522  { "get_direction", &lua_map_location::intf_get_direction },
523  { "vector_sum", &lua_map_location::intf_vector_sum },
524  { "vector_diff", &lua_map_location::intf_vector_diff },
525  { "vector_negation", &lua_map_location::intf_vector_negation },
526  { "rotate_right_around_center", &lua_map_location::intf_rotate_right_around_center },
527  { "tiles_adjacent", &lua_map_location::intf_tiles_adjacent },
528  { "get_adjacent_tiles", &lua_map_location::intf_get_adjacent_tiles },
529  { "distance_between", &lua_map_location::intf_distance_between },
530  { "get_in_basis_N_NE", &lua_map_location::intf_get_in_basis_N_NE },
531  { "get_relative_dir", &lua_map_location::intf_get_relative_dir },
532  { nullptr, nullptr }
533  };
534 
535  // Create the map_location table.
536  lua_getglobal(L, "wesnoth");
537  lua_newtable(L);
538  luaL_setfuncs(L, map_callbacks, 0);
539  lua_setfield(L, -2, "map");
540  lua_pop(L, 1);
541 
542  // Create the game_config variable with its metatable.
543  cmd_log_ << "Adding game_config table...\n";
544 
545  lua_getglobal(L, "wesnoth");
546  lua_newuserdata(L, 0);
547  lua_createtable(L, 0, 3);
548  lua_pushcfunction(L, &dispatch<&lua_kernel_base::impl_game_config_get>);
549  lua_setfield(L, -2, "__index");
550  lua_pushcfunction(L, &dispatch<&lua_kernel_base::impl_game_config_set>);
551  lua_setfield(L, -2, "__newindex");
552  lua_pushstring(L, "game config");
553  lua_setfield(L, -2, "__metatable");
554  lua_setmetatable(L, -2);
555  lua_setfield(L, -2, "game_config");
556  lua_pop(L, 1);
557 
558  // Add mersenne twister rng wrapper
559  cmd_log_ << "Adding rng tables...\n";
561 
562  cmd_log_ << "Adding name generator metatable...\n";
564  static luaL_Reg const generator[] {
565  { "__call", &impl_name_generator_call},
566  { "__gc", &impl_name_generator_collect},
567  { nullptr, nullptr}
568  };
569  luaL_setfuncs(L, generator, 0);
570 
571  // Create formula bridge metatables
573 
575 
576  // Create the Lua interpreter table
577  cmd_log_ << "Sandboxing Lua interpreter...\nTo make variables visible outside the interpreter, assign to _G.variable.\n";
578  cmd_log_ << "The special variable _ holds the result of the last expression (if any).\n";
579  lua_newtable(L);
580  lua_createtable(L, 0, 1);
581  lua_getglobal(L, "_G");
582  lua_setfield(L, -2, "__index");
583  lua_setmetatable(L, -2);
585 
586  // Loading ilua:
587  cmd_log_ << "Loading ilua...\n";
588 
589  lua_settop(L, 0);
590  luaW_getglobal(L, "wesnoth", "require");
591  lua_pushstring(L, "lua/ilua.lua");
592  if(protected_call(1, 1)) {
593  //run "ilua.set_strict()"
594  lua_pushstring(L, "set_strict");
595  lua_gettable(L, -2);
596  if (!this->protected_call(0,0, std::bind(&lua_kernel_base::log_error, this, _1, _2))) {
597  cmd_log_ << "Failed to activate strict mode.\n";
598  } else {
599  cmd_log_ << "Activated strict mode.\n";
600  }
601 
602  lua_setglobal(L, "ilua"); //save ilua table as a global
603  } else {
604  cmd_log_ << "Error: failed to load ilua.\n";
605  }
606  lua_settop(L, 0);
607 
608  // Disable functions from debug which we don't want.
609  // We do this last because ilua needs to be able to use debug.getmetatable
610  lua_getglobal(L, "debug");
611  lua_pushnil(L);
612  while(lua_next(L, -2) != 0) {
613  lua_pop(L, 1);
614  char const* function = lua_tostring(L, -1);
615  if(strcmp(function, "traceback") == 0 || strcmp(function, "getinfo") == 0) continue; //traceback is needed for our error handler
616  lua_pushnil(L); //getinfo is needed for ilua strict mode
617  lua_setfield(L, -3, function);
618  }
619  lua_pop(L, 1);
620 }
621 
623 {
624  for (const auto& pair : this->registered_widget_definitions_) {
625  gui2::remove_single_widget_definition(std::get<0>(pair), std::get<1>(pair));
626  }
627  lua_close(mState);
628 }
629 
630 void lua_kernel_base::log_error(char const * msg, char const * context)
631 {
632  ERR_LUA << context << ": " << msg << '\n';
633 }
634 
635 void lua_kernel_base::throw_exception(char const * msg, char const * context)
636 {
637  throw game::lua_error(msg, context);
638 }
639 
640 bool lua_kernel_base::protected_call(int nArgs, int nRets)
641 {
642  error_handler eh = std::bind(&lua_kernel_base::log_error, this, _1, _2 );
643  return this->protected_call(nArgs, nRets, eh);
644 }
645 
646 bool lua_kernel_base::load_string(char const * prog, const std::string& name)
647 {
648  error_handler eh = std::bind(&lua_kernel_base::log_error, this, _1, _2 );
649  return this->load_string(prog, name, eh);
650 }
651 
652 bool lua_kernel_base::protected_call(int nArgs, int nRets, error_handler e_h)
653 {
654  return this->protected_call(mState, nArgs, nRets, e_h);
655 }
656 
657 bool lua_kernel_base::protected_call(lua_State * L, int nArgs, int nRets, error_handler e_h)
658 {
659  int errcode = luaW_pcall_internal(L, nArgs, nRets);
660 
661  if (errcode != LUA_OK) {
662  char const * msg = lua_tostring(L, -1);
663 
664  std::string context = "When executing, ";
665  if (errcode == LUA_ERRRUN) {
666  context += "Lua runtime error: ";
667  } else if (errcode == LUA_ERRERR) {
668  context += "Lua error in attached debugger: ";
669  } else if (errcode == LUA_ERRMEM) {
670  context += "Lua out of memory error: ";
671  } else if (errcode == LUA_ERRGCMM) {
672  context += "Lua error in garbage collection metamethod: ";
673  } else {
674  context += "unknown lua error: ";
675  }
676  if(lua_isstring(L, -1)) {
677  context += msg ? msg : "null string";
678  } else {
679  context += lua_typename(L, lua_type(L, -1));
680  }
681 
682  lua_pop(L, 1);
683 
684  e_h(context.c_str(), "Lua Error");
685 
686  return false;
687  }
688 
689  return true;
690 }
691 
692 bool lua_kernel_base::load_string(char const * prog, const std::string& name, error_handler e_h)
693 {
694  // pass 't' to prevent loading bytecode which is unsafe and can be used to escape the sandbox.
695  int errcode = luaL_loadbufferx(mState, prog, strlen(prog), name.empty() ? name.c_str() : prog, "t");
696  if (errcode != LUA_OK) {
697  char const * msg = lua_tostring(mState, -1);
698  std::string message = msg ? msg : "null string";
699 
700  std::string context = "When parsing a string to lua, ";
701 
702  if (errcode == LUA_ERRSYNTAX) {
703  context += " a syntax error";
704  } else if(errcode == LUA_ERRMEM){
705  context += " a memory error";
706  } else if(errcode == LUA_ERRGCMM) {
707  context += " an error in garbage collection metamethod";
708  } else {
709  context += " an unknown error";
710  }
711 
712  lua_pop(mState, 1);
713 
714  e_h(message.c_str(), context.c_str());
715 
716  return false;
717  }
718  return true;
719 }
720 
722 {
723  int nArgs = 0;
724  if (const config& args = cfg.child("args")) {
725  luaW_pushconfig(this->mState, args);
726  ++nArgs;
727  }
728  this->run(cfg["code"].str().c_str(), cfg["name"].str(), nArgs);
729 }
730 // Call load_string and protected call. Make them throw exceptions.
731 //
732 void lua_kernel_base::throwing_run(const char * prog, const std::string& name, int nArgs, bool in_interpreter)
733 {
734  cmd_log_ << "$ " << prog << "\n";
735  error_handler eh = std::bind(&lua_kernel_base::throw_exception, this, _1, _2 );
736  this->load_string(prog, name, eh);
737  if(in_interpreter) {
739  if(lua_setupvalue(mState, -2, 1) == nullptr)
740  lua_pop(mState, 1);
741  }
742  lua_insert(mState, -nArgs - 1);
743  this->protected_call(nArgs, in_interpreter ? LUA_MULTRET : 0, eh);
744 }
745 
746 // Do a throwing run, but if we catch a lua_error, reformat it with signature for this function and log it.
747 void lua_kernel_base::run(const char * prog, const std::string& name, int nArgs)
748 {
749  try {
750  this->throwing_run(prog, name, nArgs);
751  } catch (const game::lua_error & e) {
752  cmd_log_ << e.what() << "\n";
753  lua_kernel_base::log_error(e.what(), "In function lua_kernel::run()");
754  }
755 }
756 
757 // Tests if a program resolves to an expression, and pretty prints it if it is, otherwise it runs it normally. Throws exceptions.
758 void lua_kernel_base::interactive_run(char const * prog) {
759  std::string experiment = "return ";
760  experiment += prog;
761  int top = lua_gettop(mState);
762 
763  error_handler eh = std::bind(&lua_kernel_base::throw_exception, this, _1, _2 );
764  luaW_getglobal(mState, "ilua", "_pretty_print");
765 
766  try {
767  // Try to load the experiment without syntax errors
768  this->load_string(experiment.c_str(), "interactive", eh);
770  if(lua_setupvalue(mState, -2, 1) == nullptr)
771  lua_pop(mState, 1);
772  } catch (const game::lua_error &) {
773  this->throwing_run(prog, "interactive", 0, true); // Since it failed, fall back to the usual throwing_run, on the original input.
774  if(lua_gettop(mState) == top + 1) {
775  // Didn't return anything
776  lua_settop(mState, top);
777  return;
778  } else goto PRINT;
779  }
780  // experiment succeeded, now run but log normally.
781  cmd_log_ << "$ " << prog << "\n";
782  this->protected_call(0, LUA_MULTRET, eh);
783 PRINT:
784  int nRets = lua_gettop(mState) - top - 1;
785  {
786  // Assign first result to _
788  int env_idx = lua_gettop(mState);
789  lua_pushvalue(mState, top + 2);
790  lua_setfield(mState, -2, "_");
791  // Now duplicate EVERY result and pass it to table.pack, assigning to _all
792  luaW_getglobal(mState, "table", "pack");
793  for(int i = top + 2; i < env_idx; i++)
795  this->protected_call(nRets, 1, eh);
796  lua_setfield(mState, -2, "_all");
797  lua_pop(mState, 1);
798  }
799  // stack is now ilua._pretty_print followed by any results of prog
800  this->protected_call(lua_gettop(mState) - top - 1, 0, eh);
801 }
802 /**
803  * Loads and executes a Lua file.
804  * - Arg 1: string containing the file name.
805  * - Ret *: values returned by executing the file body.
806  */
808 {
809  luaL_checkstring(L, 1);
810  lua_rotate(L, 1, -1);
811  if (lua_fileops::load_file(L) != 1) return 0;
812  //^ should end with the file contents loaded on the stack. actually it will call lua_error otherwise, the return 0 is redundant.
813  lua_rotate(L, 1, 1);
814  // Using a non-protected call here appears to fix an issue in plugins.
815  // The protected call isn't technically necessary anyway, because this function is called from Lua code,
816  // which should already be in a protected environment.
817  lua_call(L, lua_gettop(L) - 1, LUA_MULTRET);
818  return lua_gettop(L);
819 }
820 
821 /**
822  * Loads and executes a Lua file, if there is no corresponding entry in wesnoth.package.
823  * Stores the result of the script in wesnoth.package and returns it.
824  * - Arg 1: string containing the file name.
825  * - Ret 1: value returned by the script.
826  */
828 {
829  const char * m = luaL_checkstring(L, 1);
830  if(!m) {
831  return luaL_argerror(L, 1, "found a null string argument to wesnoth require");
832  }
833 
834  // Check if there is already an entry.
835 
836  lua_getglobal(L, "wesnoth");
837  lua_pushstring(L, "package");
838  lua_rawget(L, -2);
839  lua_pushvalue(L, 1);
840  lua_rawget(L, -2);
841  if(!lua_isnil(L, -1) && !game_config::debug_lua) {
842  return 1;
843  }
844  lua_pop(L, 1);
845  lua_pushvalue(L, 1);
846  // stack is now [packagename] [wesnoth] [package] [packagename]
847 
848  if(lua_fileops::load_file(L) != 1) {
849  // should end with the file contents loaded on the stack. actually it will call lua_error otherwise, the return 0 is redundant.
850  // stack is now [packagename] [wesnoth] [package] [chunk]
851  return 0;
852  }
853  DBG_LUA << "require: loaded a file, now calling it\n";
854 
855  if (!this->protected_call(L, 0, 1, std::bind(&lua_kernel_base::log_error, this, _1, _2))) {
856  // historically if wesnoth.require fails it just yields nil and some logging messages, not a lua error
857  return 0;
858  }
859  // stack is now [packagename] [wesnoth] [package] [results]
860 
861  lua_pushvalue(L, 1);
862  lua_pushvalue(L, -2);
863  // stack is now [packagename] [wesnoth] [package] [results] [packagename] [results]
864  // Add the return value to the table.
865 
866  lua_settable(L, -4);
867  // stack is now [packagename] [wesnoth] [package] [results]
868  return 1;
869 }
871 {
872  lua_push(L, my_name());
873  return 1;
874 }
876 {
877  char const *m = luaL_checkstring(L, 2);
890  return 0;
891 }
893 {
894  std::string err_msg = "unknown modifiable property of game_config: ";
895  err_msg += luaL_checkstring(L, 2);
896  return luaL_argerror(L, 2, err_msg.c_str());
897 }
898 /**
899  * Loads the "package" package into the Lua environment.
900  * This action is inherently unsafe, as Lua scripts will now be able to
901  * load C libraries on their own, hence granting them the same privileges
902  * as the Wesnoth binary itself.
903  */
905 {
906  lua_State *L = mState;
908  lua_pushstring(L, "package");
909  lua_call(L, 1, 0);
910 }
911 
913 {
914  lua_State* L = mState;
915  lua_settop(L, 0);
916  cmd_log_ << "Loading core...\n";
917  luaW_getglobal(L, "wesnoth", "require");
918  lua_pushstring(L, "lua/core.lua");
919  if(!protected_call(1, 1)) {
920  cmd_log_ << "Error: Failed to load core.\n";
921  }
922  lua_settop(L, 0);
923 }
924 
925 /**
926  * Gets all the global variable names in the Lua environment. This is useful for tab completion.
927  */
928 std::vector<std::string> lua_kernel_base::get_global_var_names()
929 {
930  std::vector<std::string> ret;
931 
932  lua_State *L = mState;
933 
934  int idx = lua_gettop(L);
935  lua_getglobal(L, "_G");
936  lua_pushnil(L);
937 
938  while (lua_next(L, idx+1) != 0) {
939  if (lua_isstring(L, -2)) {
940  ret.push_back(lua_tostring(L,-2));
941  }
942  lua_pop(L,1);
943  }
944  lua_settop(L, idx);
945  return ret;
946 }
947 
948 /**
949  * Gets all attribute names of an extended variable name. This is useful for tab completion.
950  */
951 std::vector<std::string> lua_kernel_base::get_attribute_names(const std::string & input)
952 {
953  std::vector<std::string> ret;
954  std::string base_path = input;
955  std::size_t last_dot = base_path.find_last_of('.');
956  std::string partial_name = base_path.substr(last_dot + 1);
957  base_path.erase(last_dot);
958  std::string load = "return " + base_path;
959 
960  lua_State* L = mState;
961  int save_stack = lua_gettop(L);
962  int result = luaL_loadstring(L, load.c_str());
963  if(result != LUA_OK) {
964  // This isn't at error level because it's a really low priority error; it just means the user tried to tab-complete something that doesn't exist.
965  LOG_LUA << "Error when attempting tab completion:\n";
966  LOG_LUA << luaL_checkstring(L, -1) << '\n';
967  // Just return an empty list; no matches were found
968  lua_settop(L, save_stack);
969  return ret;
970  }
971 
972  luaW_pcall(L, 0, 1);
973  if(lua_istable(L, -1) || lua_isuserdata(L, -1)) {
974  int top = lua_gettop(L);
975  int obj = lua_absindex(L, -1);
976  if(luaL_getmetafield(L, obj, "__tab_enum") == LUA_TFUNCTION) {
977  lua_pushvalue(L, obj);
978  lua_pushlstring(L, partial_name.c_str(), partial_name.size());
979  luaW_pcall(L, 2, 1);
980  ret = lua_check<std::vector<std::string>>(L, -1);
981  } else if(lua_type(L, -1) != LUA_TTABLE) {
982  LOG_LUA << "Userdata missing __tab_enum meta-function for tab completion";
983  lua_settop(L, save_stack);
984  return ret;
985  } else {
986  lua_settop(L, top);
987  // Metafunction not found, so use lua_next to enumerate the table
988  for(lua_pushnil(L); lua_next(L, obj); lua_pop(L, 1)) {
989  if(lua_type(L, -2) == LUA_TSTRING) {
990  std::string attr = lua_tostring(L, -2);
991  if(attr.empty()) {
992  continue;
993  }
994  if(!isalpha(attr[0]) && attr[0] != '_') {
995  continue;
996  }
997  if(std::any_of(attr.begin(), attr.end(), [](char c){
998  return !isalpha(c) && !isdigit(c) && c != '_';
999  })) {
1000  continue;
1001  }
1002  if(attr.substr(0, partial_name.size()) == partial_name) {
1003  ret.push_back(base_path + "." + attr);
1004  }
1005  }
1006  }
1007  }
1008  }
1009  lua_settop(L, save_stack);
1010  return ret;
1011 }
1012 
1014 {
1015  #ifdef __GNUC__
1016  #pragma GCC diagnostic push
1017  #pragma GCC diagnostic ignored "-Wold-style-cast"
1018  #endif
1019  return *reinterpret_cast<lua_kernel_base**>(lua_getextraspace(L));
1020  #ifdef __GNUC__
1021  #pragma GCC diagnostic pop
1022  #endif
1023 }
1024 
1026 {
1027  return seed_rng::next_seed();
1028 }
int dispatch(lua_State *L)
int intf_set_dialog_active(lua_State *L)
Sets a widget&#39;s state to active or inactive.
Definition: lua_gui2.cpp:848
VERSION_COMP_OP
void interactive_run(char const *prog)
Tests if a program resolves to an expression, and pretty prints it if it is, otherwise it runs it nor...
LUALIB_API void luaL_requiref(lua_State *L, const char *modname, lua_CFunction openf, int glb)
Definition: lauxlib.cpp:971
#define lua_isnoneornil(L, n)
Definition: lua.h:359
surface get_image(const image::locator &i_locator, TYPE type)
function to get the surface corresponding to an image.
Definition: picture.cpp:833
static int intf_name_generator(lua_State *L)
LUA_API void lua_createtable(lua_State *L, int narray, int nrec)
Definition: lapi.cpp:684
#define lua_pushcfunction(L, f)
Definition: lua.h:350
int show_lua_console(lua_State *, lua_kernel_base *lk)
Definition: lua_gui2.cpp:913
config & child(config_key_type key, int n=0)
Returns the nth child with the given key, or a reference to an invalid config if there is none...
Definition: config.cpp:420
std::string register_tstring_metatable(lua_State *L)
Adds the tstring metatable.
Definition: lua_common.cpp:430
int intf_add_dialog_tree_node(lua_State *L)
Sets a widget&#39;s state to active or inactive.
Definition: lua_gui2.cpp:932
int intf_read_file(lua_State *L)
Reads a file into a string, or a directory into a list of files therein.
LUALIB_API lua_State * luaL_newstate(void)
Definition: lauxlib.cpp:1026
LUAMOD_API int luaopen_debug(lua_State *L)
Definition: ldblib.cpp:452
void luaW_pushconfig(lua_State *L, const config &cfg)
Converts a config object to a Lua table pushed at the top of the stack.
Definition: lua_common.cpp:730
LUA_API void lua_settop(lua_State *L, int idx)
Definition: lapi.cpp:172
#define lua_isnone(L, n)
Definition: lua.h:358
LUA_API int lua_type(lua_State *L, int idx)
Definition: lapi.cpp:251
int village_support
Definition: game_config.cpp:55
bool luaW_pcall(lua_State *L, int nArgs, int nRets, bool allow_wml_error)
Calls a Lua function stored below its nArgs arguments at the top of the stack.
int intf_have_file(lua_State *L)
Checks if a file exists (not necessarily a Lua script).
Interfaces for manipulating version numbers of engine, add-ons, etc.
static int intf_get_image_size(lua_State *L)
Gets the dimension of an image.
LUALIB_API int luaL_loadstring(lua_State *L, const char *s)
Definition: lauxlib.cpp:764
int intf_canonical_path(lua_State *L)
LUA_API void lua_pushboolean(lua_State *L, int b)
Definition: lapi.cpp:557
VERSION_COMP_OP parse_version_op(const std::string &op_str)
#define LUA_MULTRET
Definition: lua.h:34
std::vector< game_tip > load(const config &cfg)
Loads the tips from a config.
Definition: tips.cpp:35
std::function< void(char const *, char const *)> error_handler
logger & info()
Definition: log.cpp:90
std::string generate(const std::map< std::string, std::string > &variables) const
int show_dialog(lua_State *L)
Displays a window.
Definition: lua_gui2.cpp:234
int intf_get_direction(lua_State *L)
Expose map_location::get_direction function to lua Arg 1: a location Arg 2: a direction Arg 3: (optio...
LUALIB_API int luaL_getmetafield(lua_State *L, int obj, const char *event)
Definition: lauxlib.cpp:772
LUA_API int lua_gettop(lua_State *L)
Definition: lapi.cpp:167
LUA_API int lua_gettable(lua_State *L, int idx)
Definition: lapi.cpp:612
LUAMOD_API int luaopen_math(lua_State *L)
Definition: lmathlib.cpp:398
LUA_API int lua_getglobal(lua_State *L, const char *name)
Definition: lapi.cpp:605
LUA_API void lua_settable(lua_State *L, int idx)
Definition: lapi.cpp:766
#define return_string_attrib(name, accessor)
Definition: lua_common.hpp:217
int intf_textdomain(lua_State *L)
Creates an interface for gettext.
Definition: lua_common.cpp:93
#define LOG_LUA
std::vector< std::tuple< std::string, std::string > > registered_widget_definitions_
LUA_API int lua_rawget(lua_State *L, int idx)
Definition: lapi.cpp:647
#define luaL_getmetatable(L, n)
Definition: lauxlib.h:135
int intf_kernel_type(lua_State *L)
virtual ~lua_kernel_base()
LUALIB_API lua_Integer luaL_optinteger(lua_State *L, int arg, lua_Integer def)
Definition: lauxlib.cpp:440
static void msg(const char *act, debug_info &i, const char *to="", const char *result="")
Definition: debugger.cpp:109
#define LUA_TFUNCTION
Definition: lua.h:70
LUA_API int lua_isuserdata(lua_State *L, int idx)
Definition: lapi.cpp:289
int intf_remove_dialog_item(lua_State *L)
Removes an entry from a list.
Definition: lua_gui2.cpp:682
void lua_push(lua_State *L, const T &val)
Definition: push_check.hpp:371
int intf_set_dialog_markup(lua_State *L)
Enables/disables Pango markup on the label of a widget of the current dialog.
Definition: lua_gui2.cpp:793
#define LOG_STREAM(level, domain)
Definition: log.hpp:189
static lg::log_domain log_scripting_lua("scripting/lua")
bool do_version_check(const version_info &a, VERSION_COMP_OP op, const version_info &b)
int luaW_open(lua_State *L)
Definition: lua_gui2.cpp:971
LUA_API int lua_absindex(lua_State *L, int idx)
Definition: lapi.cpp:160
std::vector< std::string > split(const std::string &val, const char c, const int flags)
Splits a (comma-)separated string into a vector of pieces.
int intf_vector_diff(lua_State *L)
Expose map_location::vector_difference to lua.
LUAMOD_API int luaopen_base(lua_State *L)
Definition: lbaselib.cpp:486
int rest_heal_amount
Definition: game_config.cpp:61
LUA_API void * lua_newuserdata(lua_State *L, size_t size)
Definition: lapi.cpp:1184
int intf_distance_between(lua_State *L)
Expose map_location distance_between.
void remove_single_widget_definition(const std::string &widget_type, const std::string &definition_id)
Removes a widget definition from the default GUI.
#define lua_pop(L, n)
Definition: lua.h:344
int intf_set_dialog_focus(lua_State *L)
Sets a widget to have the focus.
Definition: lua_gui2.cpp:836
int intf_rotate_right_around_center(lua_State *L)
Expose map_location::rotate_right_around_center to lua.
lua_CFunction func
Definition: lauxlib.h:33
int intf_eval_formula(lua_State *)
Evaluates a formula in the formula engine.
int intf_get_relative_dir(lua_State *L)
Expose map_location get_relative_dir.
#define LUA_TSTRING
Definition: lua.h:68
LUAMOD_API int luaopen_coroutine(lua_State *L)
Definition: lcorolib.cpp:164
LUALIB_API int luaL_argerror(lua_State *L, int arg, const char *extramsg)
Definition: lauxlib.cpp:164
LUAMOD_API int luaopen_os(lua_State *L)
Definition: loslib.cpp:405
std::string deprecated_message(const std::string &elem_name, DEP_LEVEL level, const version_info &version, const std::string &detail)
Definition: deprecation.cpp:29
#define return_int_attrib(name, accessor)
Definition: lua_common.hpp:226
void load_core()
Loads the "core" library into the Lua environment.
bool luaW_getglobal(lua_State *L, const std::vector< std::string > &path)
Pushes the value found by following the variadic names (char *), if the value is not nil...
Definition: lua_common.cpp:871
LUAMOD_API int luaopen_string(lua_State *L)
Definition: lstrlib.cpp:1579
LUA_API int lua_isstring(lua_State *L, int idx)
Definition: lapi.cpp:283
int luaW_open(lua_State *L)
static int intf_get_language(lua_State *L)
LUALIB_API int luaL_loadbufferx(lua_State *L, const char *buff, size_t size, const char *name, const char *mode)
Definition: lauxlib.cpp:755
int intf_show_lua_console(lua_State *L)
static lg::log_domain log_user("scripting/lua/user")
virtual ~name_generator()
LUAMOD_API int luaopen_table(lua_State *L)
Definition: ltablib.cpp:441
t_string luaW_checktstring(lua_State *L, int index)
Converts a scalar to a translatable string.
Definition: lua_common.cpp:620
static int intf_deprecated_message(lua_State *L)
Logs a deprecation message.
LUAMOD_API int luaopen_package(lua_State *L)
Definition: loadlib.cpp:767
void load_package()
Loads the package library into lua environment.
LUA_API void lua_close(lua_State *L)
Definition: lstate.cpp:341
bool protected_call(int nArgs, int nRets, error_handler)
int intf_set_dialog_tooltip(lua_State *L)
Sets the value of a widget on the current dialog.
Definition: lua_gui2.cpp:573
#define lua_getextraspace(L)
Definition: lua.h:339
LUA_API const char * lua_pushlstring(lua_State *L, const char *s, size_t len)
Definition: lapi.cpp:479
int kill_experience
Definition: game_config.cpp:57
LUA_API void lua_setglobal(lua_State *L, const char *name)
Definition: lapi.cpp:759
std::string register_metatables(lua_State *L)
Definition: lua_color.cpp:135
LUA_API int lua_setmetatable(lua_State *L, int objindex)
Definition: lapi.cpp:846
static int impl_name_generator_collect(lua_State *L)
const char * what() const noexcept
Definition: exceptions.hpp:37
int intf_compile_formula(lua_State *)
int(lua_kernel_base::* member_callback)(lua_State *L)
int intf_set_dialog_canvas(lua_State *L)
Sets a canvas on a widget of the current dialog.
Definition: lua_gui2.cpp:812
int luaW_pcall_internal(lua_State *L, int nArgs, int nRets)
#define lua_newtable(L)
Definition: lua.h:346
int luaW_open(lua_State *L)
Definition: lua_wml.cpp:244
LUA_API void lua_pushnil(lua_State *L)
Definition: lapi.cpp:450
LUA_API const char * lua_setupvalue(lua_State *L, int funcindex, int n)
Definition: lapi.cpp:1236
int intf_tiles_adjacent(lua_State *L)
Expose map_location tiles_adjacent.
LUAMOD_API int() luaopen_utf8(lua_State *L)
Definition: lutf8lib.cpp:250
virtual int impl_game_config_get(lua_State *L)
#define LUA_ERRGCMM
Definition: lua.h:52
int intf_vector_negation(lua_State *L)
Expose map_location::vector_negation to lua.
LUALIB_API int luaL_newmetatable(lua_State *L, const char *tname)
Definition: lauxlib.cpp:299
LUA_API void * lua_touserdata(lua_State *L, int idx)
Definition: lapi.cpp:413
#define LUA_ERRERR
Definition: lua.h:53
void run(char const *prog, const std::string &name, int nArgs=0)
Runs a plain script.
static int intf_random(lua_State *L)
Returns a random numer, same interface as math.random.
#define lua_isnil(L, n)
Definition: lua.h:355
int intf_print(lua_State *L)
Replacement print function – instead of printing to std::cout, print to the command log...
std::size_t i
Definition: function.cpp:933
int intf_set_dialog_value(lua_State *L)
Sets the value of a widget on the current dialog.
Definition: lua_gui2.cpp:444
logger & err()
Definition: log.cpp:78
LUALIB_API lua_Integer luaL_checkinteger(lua_State *L, int arg)
Definition: lauxlib.cpp:430
std::string register_metatables(lua_State *)
std::string register_gettext_metatable(lua_State *L)
Adds the gettext metatable.
Definition: lua_common.cpp:410
int village_income
Definition: game_config.cpp:54
int intf_get_in_basis_N_NE(lua_State *L)
Expose map_location get_in_basis_N_NE.
static map_location::DIRECTION s
const language_def & get_language()
Definition: language.cpp:316
virtual uint32_t get_random_seed()
#define LUA_ERRSYNTAX
Definition: lua.h:50
#define lua_tostring(L, i)
Definition: lua.h:366
static int intf_get_time_stamp(lua_State *L)
Returns the time stamp, exactly as [set_variable] time=stamp does.
static int intf_compare_versions(lua_State *L)
Compares 2 version strings - which is newer.
void throwing_run(char const *prog, const std::string &name, int nArgs, bool in_interpreter=false)
Runs a plain script, but reports errors by throwing lua_error.
LUA_API void lua_rotate(lua_State *L, int idx, int n)
Definition: lapi.cpp:207
int combat_experience
Definition: game_config.cpp:58
LUA_API void lua_pushvalue(lua_State *L, int idx)
Definition: lapi.cpp:237
const bool & debug
#define debug(x)
#define LUA_ERRMEM
Definition: lua.h:51
int intf_get_adjacent_tiles(lua_State *L)
Expose map_location get_adjacent_tiles.
int load_file(lua_State *L)
Loads a Lua file and pushes the contents on the stack.
LUA_API int lua_isnumber(lua_State *L, int idx)
Definition: lapi.cpp:276
virtual void log_error(char const *msg, char const *context="Lua error")
Error reporting mechanisms, used by virtual methods protected_call and load_string.
const version_info wesnoth_version(VERSION)
rng * generator
This generator is automatically synced during synced context.
Definition: random.cpp:60
bool load_string(char const *prog, const std::string &name, error_handler)
#define lua_call(L, n, r)
Definition: lua.h:274
int intf_set_dialog_callback(lua_State *L)
Sets a callback on a widget of the current dialog.
Definition: lua_gui2.cpp:742
virtual int impl_game_config_set(lua_State *L)
#define DBG_LUA
Represents version numbers.
std::vector< std::string > get_global_var_names()
Get tab completion strings.
command_log cmd_log_
int intf_vector_sum(lua_State *L)
Expose map_location::vector_sum to lua.
#define LUA_REGISTRYINDEX
Definition: lua.h:42
#define return_bool_attrib(name, accessor)
Definition: lua_common.hpp:242
static int impl_name_generator_call(lua_State *L)
uint32_t next_seed()
Definition: seed_rng.cpp:45
LUA_API int lua_error(lua_State *L)
Definition: lapi.cpp:1114
logger & warn()
Definition: log.cpp:84
std::vector< std::string > get_attribute_names(const std::string &var_path)
Gets all attribute names of an extended variable name.
#define LUA_OK
Definition: lua.h:47
#define lua_istable(L, n)
Definition: lua.h:353
DEP_LEVEL
See https://wiki.wesnoth.org/CompatibilityStandards for more info.
Definition: deprecation.hpp:19
virtual void throw_exception(char const *msg, char const *context="Lua error")
#define lua_insert(L, idx)
Definition: lua.h:369
Standard logging facilities (interface).
std::string str() const
Serializes the version number into string form.
uint32_t next_random()
Provides the next random draw.
Definition: random.cpp:84
void register_metatable(lua_State *L)
#define ERR_LUA
virtual std::string my_name()
User-visible name of the lua kernel that they are talking to.
#define e
int intf_get_dialog_value(lua_State *L)
Gets the value of a widget on the current dialog.
Definition: lua_gui2.cpp:591
LUALIB_API void luaL_setfuncs(lua_State *L, const luaL_Reg *l, int nup)
Definition: lauxlib.cpp:934
void push_error_handler(lua_State *L)
A config object defines a single node in a WML file, with access to child nodes.
Definition: config.hpp:68
int intf_dofile(lua_State *L)
Loads and executes a Lua file.
mock_char c
static const char * Interp
LUA_API int lua_getfield(lua_State *L, int idx, const char *k)
Definition: lapi.cpp:622
lua_State * mState
static int intf_load(lua_State *L)
Replacement load function.
#define LUA_TTABLE
Definition: lua.h:69
LUA_API void lua_pushinteger(lua_State *L, lua_Integer n)
Definition: lapi.cpp:466
#define luaL_optstring(L, n, d)
Definition: lauxlib.h:125
bool file_exists() const
Tests whether the file the locater points at exists.
Definition: picture.cpp:662
int intf_require(lua_State *L)
Loads and executes a Lua file, if there is no corresponding entry in wesnoth.package.
void load_tables(lua_State *L)
Creates the metatable for RNG objects, and adds the Rng table which contains the constructor.
Definition: lua_rng.cpp:80
void run_lua_tag(const config &cfg)
Runs a [lua] tag.
LUA_API const char * lua_pushstring(lua_State *L, const char *s)
Definition: lapi.cpp:491
LUA_API void lua_setfield(lua_State *L, int idx, const char *k)
Definition: lapi.cpp:777
#define LUA_ERRRUN
Definition: lua.h:49
int intf_set_dialog_visible(lua_State *L)
Sets the visiblity of a widget in the current dialog.
Definition: lua_gui2.cpp:866
LUA_API int lua_next(lua_State *L, int idx)
Definition: lapi.cpp:1123
const char * what() const noexcept
static lua_kernel_base *& get_lua_kernel_base_ptr(lua_State *L)
LUA_API const char * lua_typename(lua_State *L, int t)
Definition: lapi.cpp:257
static const char * Gen
std::vector< std::string > parenthetical_split(const std::string &val, const char separator, const std::string &left, const std::string &right, const int flags)
Splits a string based either on a separator, except then the text appears within specified parenthesi...
static int intf_log(lua_State *L)
Logs a message Arg 1: (optional) Logger Arg 2: Message.
#define luaL_checkstring(L, n)
Definition: lauxlib.h:124
Error used to report an error in a lua script or in the lua interpreter.
Definition: game_errors.hpp:53