The Battle for Wesnoth  1.15.0-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"
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 
26 #ifdef DEBUG_LUA
27 #include "scripting/debug_lua.hpp"
28 #endif
29 
30 #include "scripting/lua_common.hpp"
34 #include "scripting/lua_gui2.hpp"
36 #include "scripting/lua_rng.hpp"
37 #include "scripting/push_check.hpp"
38 
39 #include "game_version.hpp" // for do_version_check, etc
40 #include "picture.hpp"
41 
42 #include "formula/string_utils.hpp"
43 #include "utils/functional.hpp"
44 #include "utils/name_generator.hpp"
47 #include "variable.hpp" // for config_variable_set
48 
49 #include <cstring>
50 #include <exception>
51 #include <new>
52 #include <string>
53 #include <sstream>
54 #include <vector>
55 
56 #include "lua/lauxlib.h"
57 #include "lua/lua.h"
58 #include "lua/lualib.h"
59 
60 static lg::log_domain log_scripting_lua("scripting/lua");
61 static lg::log_domain log_user("scripting/lua/user");
62 #define DBG_LUA LOG_STREAM(debug, log_scripting_lua)
63 #define LOG_LUA LOG_STREAM(info, log_scripting_lua)
64 #define WRN_LUA LOG_STREAM(warn, log_scripting_lua)
65 #define ERR_LUA LOG_STREAM(err, log_scripting_lua)
66 
67 // Registry key for metatable
68 static const char * Gen = "name generator";
69 
70 // Callback implementations
71 
72 /**
73  * Compares 2 version strings - which is newer.
74  * - Args 1,3: version strings
75  * - Arg 2: comparison operator (string)
76  * - Ret 1: comparison result
77  */
79 {
80  char const *v1 = luaL_checkstring(L, 1);
81 
83  if(vop == OP_INVALID) return luaL_argerror(L, 2, "unknown version comparison operator - allowed are ==, !=, <, <=, > and >=");
84 
85  char const *v2 = luaL_checkstring(L, 3);
86 
87  const bool result = do_version_check(version_info(v1), vop, version_info(v2));
88  lua_pushboolean(L, result);
89 
90  return 1;
91 }
92 
93 /**
94  * Replacement print function -- instead of printing to std::cout, print to the command log.
95  * Intended to be bound to this' command_log at registration time.
96  */
98 {
99  DBG_LUA << "intf_print called:\n";
100  std::size_t nargs = lua_gettop(L);
101 
102  lua_getglobal(L, "tostring");
103  for (std::size_t i = 1; i <= nargs; ++i) {
104  lua_pushvalue(L, -1); // function to call: "tostring"
105  lua_pushvalue(L, i); // value to pass through tostring() before printing
106  lua_call(L, 1, 1);
107  const char * str = lua_tostring(L, -1);
108  if (!str) {
109  LOG_LUA << "'tostring' must return a value to 'print'\n";
110  str = "";
111  }
112  if (i > 1) {
113  cmd_log_ << "\t"; //separate multiple args with tab character
114  }
115  cmd_log_ << str;
116  DBG_LUA << "'" << str << "'\n";
117  lua_pop(L, 1); // Pop the output of tostrring()
118  }
119  lua_pop(L, 1); // Pop 'tostring' global
120 
121  cmd_log_ << "\n";
122  DBG_LUA << "\n";
123 
124  return 0;
125 }
126 
127 /**
128  * Replacement load function. Mostly the same as regular load, but disallows loading binary chunks
129  * due to CVE-2018-1999023.
130  */
131 static int intf_load(lua_State* L)
132 {
133  std::string chunk = luaL_checkstring(L, 1);
134  const char* name = luaL_optstring(L, 2, chunk.c_str());
135  std::string mode = luaL_optstring(L, 3, "t");
136  bool override_env = !lua_isnone(L, 4);
137 
138  if(mode != "t") {
139  return luaL_argerror(L, 3, "binary chunks are not allowed for security reasons");
140  }
141 
142  int result = luaL_loadbufferx(L, chunk.data(), chunk.length(), name, "t");
143  if(result != LUA_OK) {
144  lua_pushnil(L);
145  // Move the nil as the first return value, like Lua's own load() does.
146  lua_insert(L, -2);
147 
148  return 2;
149  }
150 
151  if(override_env) {
152  // Copy "env" to the top of the stack.
153  lua_pushvalue(L, 4);
154  // Set "env" as the first upvalue.
155  const char* upvalue_name = lua_setupvalue(L, -2, 1);
156  if(upvalue_name == nullptr) {
157  // lua_setupvalue() didn't remove the copy of "env" from the stack, so we need to do it ourselves.
158  lua_pop(L, 1);
159  }
160  }
161 
162  return 1;
163 }
164 
165 // The show lua console callback is similarly a method of lua kernel
167 {
168  if (cmd_log_.external_log_) {
169  std::string message = "There is already an external logger attached to this lua kernel, you cannot open the lua console right now.";
170  log_error(message.c_str());
171  cmd_log_ << message << "\n";
172  return 0;
173  }
174 
175  return lua_gui2::show_lua_console(L, this);
176 }
177 
179 {
180  name_generator* gen = static_cast<name_generator*>(lua_touserdata(L, 1));
181  lua_pushstring(L, gen->generate().c_str());
182  return 1;
183 }
184 
186 {
187  name_generator* gen = static_cast<name_generator*>(lua_touserdata(L, 1));
188  gen->~name_generator();
189  return 0;
190 }
191 
193 {
194  std::string type = luaL_checkstring(L, 1);
195  name_generator* gen = nullptr;
196  try {
197  if(type == "markov" || type == "markov_chain") {
198  std::vector<std::string> input;
199  if(lua_istable(L, 2)) {
200  input = lua_check<std::vector<std::string>>(L, 2);
201  } else {
202  input = utils::parenthetical_split(luaL_checkstring(L, 2), ',');
203  }
204  int chain_sz = luaL_optinteger(L, 3, 2);
205  int max_len = luaL_optinteger(L, 4, 12);
206  gen = new(L) markov_generator(input, chain_sz, max_len);
207  // Ensure the pointer didn't change when cast
208  assert(static_cast<void*>(gen) == dynamic_cast<markov_generator*>(gen));
209  } else if(type == "context_free" || type == "cfg" || type == "CFG") {
210  if(lua_istable(L, 2)) {
211  std::map<std::string, std::vector<std::string>> data;
212  for(lua_pushnil(L); lua_next(L, 2); lua_pop(L, 1)) {
213  if(lua_type(L, -2) != LUA_TSTRING) {
214  lua_pushstring(L, "CFG generator: invalid nonterminal name (must be a string)");
215  return lua_error(L);
216  }
217  if(lua_isstring(L, -1)) {
218  data[lua_tostring(L,-2)] = utils::split(lua_tostring(L,-1),'|');
219  } else if(lua_istable(L, -1)) {
220  data[lua_tostring(L,-2)] = lua_check<std::vector<std::string>>(L, -1);
221  } else {
222  lua_pushstring(L, "CFG generator: invalid noterminal value (must be a string or list of strings)");
223  return lua_error(L);
224  }
225  }
226  if(!data.empty()) {
227  gen = new(L) context_free_grammar_generator(data);
228  }
229  } else {
231  }
232  if(gen) {
233  assert(static_cast<void*>(gen) == dynamic_cast<context_free_grammar_generator*>(gen));
234  }
235  } else {
236  return luaL_argerror(L, 1, "should be either 'markov_chain' or 'context_free'");
237  }
238  }
239  catch (const name_generator_invalid_exception& ex) {
240  lua_pushstring(L, ex.what());
241  return lua_error(L);
242  }
243 
244  // We set the metatable now, even if the generator is invalid, so that it
245  // will be properly collected if it was invalid.
247  lua_setmetatable(L, -2);
248 
249  return 1;
250 }
251 
252 /**
253 * Returns a random numer, same interface as math.random.
254 */
255 static int intf_random(lua_State *L)
256 {
257  if (lua_isnoneornil(L, 1)) {
258  double r = static_cast<double>(randomness::generator->next_random());
259  double r_max = static_cast<double>(std::numeric_limits<uint32_t>::max());
260  lua_push(L, r / (r_max + 1));
261  return 1;
262  }
263  else {
264  int32_t min;
265  int32_t max;
266  if (lua_isnumber(L, 2)) {
267  min = lua_check<int32_t>(L, 1);
268  max = lua_check<int32_t>(L, 2);
269  }
270  else {
271  min = 1;
272  max = lua_check<int32_t>(L, 1);
273  }
274  if (min > max) {
275  return luaL_argerror(L, 1, "min > max");
276  }
277  lua_push(L, randomness::generator->get_random_int(min, max));
278  return 1;
279  }
280 }
281 
283 {
284  config cfg = luaW_checkconfig(L, 1);
285  config filter = luaW_checkconfig(L, 2);
286  lua_pushboolean(L, cfg.matches(filter));
287  return 1;
288 }
289 
290 /**
291 * Logs a message
292 * Arg 1: (optional) Logger
293 * Arg 2: Message
294 */
295 static int intf_log(lua_State *L) {
296  const std::string& logger = lua_isstring(L, 2) ? luaL_checkstring(L, 1) : "";
297  std::string msg = lua_isstring(L, 2) ? luaL_checkstring(L, 2) : luaL_checkstring(L, 1);
298  if(msg.empty() || msg.back() != '\n') {
299  msg += '\n';
300  }
301 
302  if(logger == "err" || logger == "error") {
303  LOG_STREAM(err, log_user) << msg;
304  } else if(logger == "warn" || logger == "wrn" || logger == "warning") {
306  } else if((logger == "debug" || logger == "dbg")) {
308  } else {
310  }
311  return 0;
312 }
313 
314 /**
315  * Logs a deprecation message. See deprecation.cpp for details
316  * Arg 1: Element to be deprecated.
317  * Arg 2: Deprecation level.
318  * Arg 3: Version when element may be removed.
319  * Arg 4: Additional detail message.
320  */
322  const std::string elem = luaL_checkstring(L, 1);
323  // This could produce an invalid deprecation level, but that possibility is handled in deprecated_message()
325  const std::string ver_str = lua_isnoneornil(L, 3) ? "" : luaL_checkstring(L, 3);
326  const std::string detail = luaW_checktstring(L, 4);
327  const version_info ver = ver_str.empty() ? game_config::wesnoth_version.str() : ver_str;
328  const std::string msg = deprecated_message(elem, level, ver, detail);
329  if(level < DEP_LEVEL::INDEFINITE || level >= DEP_LEVEL::REMOVED) {
330  // Invalid deprecation level or level 4 deprecation should raise an interpreter error
331  lua_push(L, msg);
332  return lua_error(L);
333  }
334  return 0;
335 }
336 
337 /**
338 * Gets the dimension of an image.
339 * - Arg 1: string.
340 * - Ret 1: width.
341 * - Ret 2: height.
342 */
344  char const *m = luaL_checkstring(L, 1);
345  image::locator img(m);
346  if(!img.file_exists()) return 0;
347  surface s = get_image(img);
348  lua_pushinteger(L, s->w);
349  lua_pushinteger(L, s->h);
350  return 2;
351 }
352 
353 /**
354 * Returns the time stamp, exactly as [set_variable] time=stamp does.
355 * - Ret 1: integer
356 */
358  lua_pushinteger(L, SDL_GetTicks());
359  return 1;
360 }
361 
362 static int intf_format(lua_State* L)
363 {
364  config cfg = luaW_checkconfig(L, 2);
365  config_variable_set variables(cfg);
366  if(lua_isstring(L, 1)) {
367  std::string str = lua_tostring(L, 1);
369  return 1;
370  }
371  t_string str = luaW_checktstring(L, 1);
373  return 1;
374 }
375 
376 template<bool conjunct>
378 {
379  const t_string empty = luaW_checktstring(L, 1);
380  auto values = lua_check<std::vector<t_string>>(L, 2);
381  lua_push(L, (conjunct ? utils::format_conjunct_list : utils::format_disjunct_list)(empty, values));
382  return 1;
383 }
384 
385 /**
386 * Dumps a wml table or userdata wml object into a pretty string.
387 * - Arg 1: wml table or vconfig userdata
388 * - Ret 1: string
389 */
390 static int intf_debug(lua_State* L) {
391  const config& arg = luaW_checkconfig(L, 1);
392  const std::string& result = arg.debug();
393  lua_pushstring(L, result.c_str());
394  return 1;
395 }
396 
397 // End Callback implementations
398 
399 // Template which allows to push member functions to the lua kernel base into lua as C functions, using a shim
401 
402 template <member_callback method>
404  return ((lua_kernel_base::get_lua_kernel<lua_kernel_base>(L)).*method)(L);
405 }
406 
407 // Ctor, initialization
409  : mState(luaL_newstate())
410  , cmd_log_()
411 {
413  lua_State *L = mState;
414 
415  cmd_log_ << "Initializing " << my_name() << "...\n";
416 
417  // Open safe libraries.
418  // Debug and OS are not, but most of their functions will be disabled below.
419  cmd_log_ << "Adding standard libs...\n";
420 
421  static const luaL_Reg safe_libs[] {
422  { "", luaopen_base },
423  { "table", luaopen_table },
424  { "string", luaopen_string },
425  { "math", luaopen_math },
426  { "coroutine", luaopen_coroutine },
427  { "debug", luaopen_debug },
428  { "os", luaopen_os },
429  { "utf8", luaopen_utf8 }, // added in Lua 5.3
430  { nullptr, nullptr }
431  };
432  for (luaL_Reg const *lib = safe_libs; lib->func; ++lib)
433  {
434  luaL_requiref(L, lib->name, lib->func, 1);
435  lua_pop(L, 1); /* remove lib */
436  }
437 
438  // Disable functions from os which we don't want.
439  lua_getglobal(L, "os");
440  lua_pushnil(L);
441  while(lua_next(L, -2) != 0) {
442  lua_pop(L, 1);
443  char const* function = lua_tostring(L, -1);
444  if(strcmp(function, "clock") == 0 || strcmp(function, "date") == 0
445  || strcmp(function, "time") == 0 || strcmp(function, "difftime") == 0) continue;
446  lua_pushnil(L);
447  lua_setfield(L, -3, function);
448  }
449  lua_pop(L, 1);
450 
451  // Disable functions from debug which we don't want.
452  lua_getglobal(L, "debug");
453  lua_pushnil(L);
454  while(lua_next(L, -2) != 0) {
455  lua_pop(L, 1);
456  char const* function = lua_tostring(L, -1);
457  if(strcmp(function, "traceback") == 0 || strcmp(function, "getinfo") == 0) continue; //traceback is needed for our error handler
458  lua_pushnil(L); //getinfo is needed for ilua strict mode
459  lua_setfield(L, -3, function);
460  }
461  lua_pop(L, 1);
462 
463  // Delete dofile and loadfile.
464  lua_pushnil(L);
465  lua_setglobal(L, "dofile");
466  lua_pushnil(L);
467  lua_setglobal(L, "loadfile");
468 
469  // Store the error handler.
470  cmd_log_ << "Adding error handler...\n";
472 
473  // Create the gettext metatable.
475 
476  // Create the tstring metatable.
478 
479 
480  lua_settop(L, 0);
481 
482  // Define the CPP_function metatable ( so we can override print to point to a C++ member function, add "show_dialog" for this kernel, etc. )
483  cmd_log_ << "Adding boost function proxy...\n";
484 
486 
487  // Add some callback from the wesnoth lib
488  cmd_log_ << "Registering basic wesnoth API...\n";
489 
490  static luaL_Reg const callbacks[] {
491  { "compare_versions", &intf_compare_versions },
492  { "debug", &intf_debug },
493  { "deprecated_message", &intf_deprecated_message },
494  { "have_file", &lua_fileops::intf_have_file },
495  { "read_file", &lua_fileops::intf_read_file },
496  { "textdomain", &lua_common::intf_textdomain },
497  { "tovconfig", &lua_common::intf_tovconfig },
498  { "get_dialog_value", &lua_gui2::intf_get_dialog_value },
499  { "set_dialog_active", &lua_gui2::intf_set_dialog_active },
500  { "set_dialog_visible", &lua_gui2::intf_set_dialog_visible },
501  { "add_dialog_tree_node", &lua_gui2::intf_add_dialog_tree_node },
502  { "add_widget_definition", &lua_gui2::intf_add_widget_definition },
503  { "set_dialog_callback", &lua_gui2::intf_set_dialog_callback },
504  { "set_dialog_canvas", &lua_gui2::intf_set_dialog_canvas },
505  { "set_dialog_focus", &lua_gui2::intf_set_dialog_focus },
506  { "set_dialog_markup", &lua_gui2::intf_set_dialog_markup },
507  { "set_dialog_value", &lua_gui2::intf_set_dialog_value },
508  { "remove_dialog_item", &lua_gui2::intf_remove_dialog_item },
509  { "dofile", &dispatch<&lua_kernel_base::intf_dofile> },
510  { "require", &dispatch<&lua_kernel_base::intf_require> },
511  { "kernel_type", &dispatch<&lua_kernel_base::intf_kernel_type> },
512  { "show_dialog", &lua_gui2::show_dialog },
513  { "show_menu", &lua_gui2::show_menu },
514  { "show_message_dialog", &lua_gui2::show_message_dialog },
515  { "show_popup_dialog", &lua_gui2::show_popup_dialog },
516  { "show_story", &lua_gui2::show_story },
517  { "show_message_box", &lua_gui2::show_message_box },
518  { "show_lua_console", &dispatch<&lua_kernel_base::intf_show_lua_console> },
519  { "compile_formula", &lua_formula_bridge::intf_compile_formula},
520  { "eval_formula", &lua_formula_bridge::intf_eval_formula},
521  { "name_generator", &intf_name_generator },
522  { "random", &intf_random },
523  { "wml_matches_filter", &intf_wml_matches_filter },
524  { "log", &intf_log },
525  { "get_image_size", &intf_get_image_size },
526  { "get_time_stamp", &intf_get_time_stamp },
527  { "format", &intf_format },
528  { "format_conjunct_list", &intf_format_list<true> },
529  { "format_disjunct_list", &intf_format_list<false> },
530  { nullptr, nullptr }
531  };
532 
533  lua_getglobal(L, "wesnoth");
534  if (!lua_istable(L,-1)) {
535  lua_newtable(L);
536  }
537  luaL_setfuncs(L, callbacks, 0);
538  //lua_cpp::set_functions(L, cpp_callbacks, 0);
539  lua_setglobal(L, "wesnoth");
540 
541  // Override the print function
542  cmd_log_ << "Redirecting print function...\n";
543 
544  lua_getglobal(L, "print");
545  lua_setglobal(L, "std_print"); //storing original impl as 'std_print'
546  lua_settop(L, 0); //clear stack, just to be sure
547 
548  lua_pushcfunction(L, &dispatch<&lua_kernel_base::intf_print>);
549  lua_setglobal(L, "print");
550 
552  lua_setglobal(L, "load");
553  lua_pushnil(L);
554  lua_setglobal(L, "loadstring");
555 
556  cmd_log_ << "Initializing package repository...\n";
557  // Create the package table.
558  lua_getglobal(L, "wesnoth");
559  lua_newtable(L);
560  lua_setfield(L, -2, "package");
561  lua_pop(L, 1);
562  lua_settop(L, 0);
563  lua_pushstring(L, "lua/package.lua");
564  int res = intf_require(L);
565  if(res != 1) {
566  cmd_log_ << "Error: Failed to initialize package repository. Falling back to less flexible C++ implementation.\n";
567  }
568 
569  // Get some callbacks for map locations
570  cmd_log_ << "Adding map table...\n";
571 
572  static luaL_Reg const map_callbacks[] {
573  { "get_direction", &lua_map_location::intf_get_direction },
574  { "vector_sum", &lua_map_location::intf_vector_sum },
575  { "vector_diff", &lua_map_location::intf_vector_diff },
576  { "vector_negation", &lua_map_location::intf_vector_negation },
577  { "rotate_right_around_center", &lua_map_location::intf_rotate_right_around_center },
578  { "tiles_adjacent", &lua_map_location::intf_tiles_adjacent },
579  { "get_adjacent_tiles", &lua_map_location::intf_get_adjacent_tiles },
580  { "distance_between", &lua_map_location::intf_distance_between },
581  { "get_in_basis_N_NE", &lua_map_location::intf_get_in_basis_N_NE },
582  { "get_relative_dir", &lua_map_location::intf_get_relative_dir },
583  { nullptr, nullptr }
584  };
585 
586  // Create the map_location table.
587  lua_getglobal(L, "wesnoth");
588  lua_newtable(L);
589  luaL_setfuncs(L, map_callbacks, 0);
590  lua_setfield(L, -2, "map");
591  lua_pop(L, 1);
592 
593  // Create the game_config variable with its metatable.
594  cmd_log_ << "Adding game_config table...\n";
595 
596  lua_getglobal(L, "wesnoth");
597  lua_newuserdata(L, 0);
598  lua_createtable(L, 0, 3);
599  lua_pushcfunction(L, &dispatch<&lua_kernel_base::impl_game_config_get>);
600  lua_setfield(L, -2, "__index");
601  lua_pushcfunction(L, &dispatch<&lua_kernel_base::impl_game_config_set>);
602  lua_setfield(L, -2, "__newindex");
603  lua_pushstring(L, "game config");
604  lua_setfield(L, -2, "__metatable");
605  lua_setmetatable(L, -2);
606  lua_setfield(L, -2, "game_config");
607  lua_pop(L, 1);
608 
609  // Add mersenne twister rng wrapper
610  cmd_log_ << "Adding rng tables...\n";
612 
613  cmd_log_ << "Adding name generator metatable...\n";
615  static luaL_Reg const generator[] {
616  { "__call", &impl_name_generator_call},
617  { "__gc", &impl_name_generator_collect},
618  { nullptr, nullptr}
619  };
620  luaL_setfuncs(L, generator, 0);
621 
622  // Create formula bridge metatables
624 
625  // Loading ilua:
626  cmd_log_ << "Loading ilua...\n";
627 
628  lua_settop(L, 0);
629  luaW_getglobal(L, "wesnoth", "require");
630  lua_pushstring(L, "lua/ilua.lua");
631  if(protected_call(1, 1)) {
632  //run "ilua.set_strict()"
633  lua_pushstring(L, "set_strict");
634  lua_gettable(L, -2);
635  if (!this->protected_call(0,0, std::bind(&lua_kernel_base::log_error, this, _1, _2))) {
636  cmd_log_ << "Failed to activate strict mode.\n";
637  } else {
638  cmd_log_ << "Activated strict mode.\n";
639  }
640 
641  lua_setglobal(L, "ilua"); //save ilua table as a global
642  } else {
643  cmd_log_ << "Error: failed to load ilua.\n";
644  }
645  lua_settop(L, 0);
646 }
647 
649 {
650  for (const auto& pair : this->registered_widget_definitions_) {
651  gui2::remove_single_widget_definition(std::get<0>(pair), std::get<1>(pair));
652  }
653  lua_close(mState);
654 }
655 
656 void lua_kernel_base::log_error(char const * msg, char const * context)
657 {
658  ERR_LUA << context << ": " << msg << '\n';
659 }
660 
661 void lua_kernel_base::throw_exception(char const * msg, char const * context)
662 {
663  throw game::lua_error(msg, context);
664 }
665 
666 bool lua_kernel_base::protected_call(int nArgs, int nRets)
667 {
668  error_handler eh = std::bind(&lua_kernel_base::log_error, this, _1, _2 );
669  return this->protected_call(nArgs, nRets, eh);
670 }
671 
672 bool lua_kernel_base::load_string(char const * prog)
673 {
674  error_handler eh = std::bind(&lua_kernel_base::log_error, this, _1, _2 );
675  return this->load_string(prog, eh);
676 }
677 
678 bool lua_kernel_base::protected_call(int nArgs, int nRets, error_handler e_h)
679 {
680  return this->protected_call(mState, nArgs, nRets, e_h);
681 }
682 
683 bool lua_kernel_base::protected_call(lua_State * L, int nArgs, int nRets, error_handler e_h)
684 {
685  int errcode = luaW_pcall_internal(L, nArgs, nRets);
686 
687  if (errcode != LUA_OK) {
688  char const * msg = lua_tostring(L, -1);
689 
690  std::string context = "When executing, ";
691  if (errcode == LUA_ERRRUN) {
692  context += "Lua runtime error: ";
693  } else if (errcode == LUA_ERRERR) {
694  context += "Lua error in attached debugger: ";
695  } else if (errcode == LUA_ERRMEM) {
696  context += "Lua out of memory error: ";
697  } else if (errcode == LUA_ERRGCMM) {
698  context += "Lua error in garbage collection metamethod: ";
699  } else {
700  context += "unknown lua error: ";
701  }
702  if(lua_isstring(L, -1)) {
703  context += msg ? msg : "null string";
704  } else {
705  context += lua_typename(L, lua_type(L, -1));
706  }
707 
708  lua_pop(L, 1);
709 
710  e_h(context.c_str(), "Lua Error");
711 
712  return false;
713  }
714 
715  return true;
716 }
717 
718 bool lua_kernel_base::load_string(char const * prog, error_handler e_h)
719 {
720  // pass 't' to prevent loading bytecode which is unsafe and can be used to escape the sandbox.
721  // todo: maybe allow a 'name' parameter to give better error messages.
722  int errcode = luaL_loadbufferx(mState, prog, strlen(prog), /*name*/ prog, "t");
723  if (errcode != LUA_OK) {
724  char const * msg = lua_tostring(mState, -1);
725  std::string message = msg ? msg : "null string";
726 
727  std::string context = "When parsing a string to lua, ";
728 
729  if (errcode == LUA_ERRSYNTAX) {
730  context += " a syntax error";
731  } else if(errcode == LUA_ERRMEM){
732  context += " a memory error";
733  } else if(errcode == LUA_ERRGCMM) {
734  context += " an error in garbage collection metamethod";
735  } else {
736  context += " an unknown error";
737  }
738 
739  lua_pop(mState, 1);
740 
741  e_h(message.c_str(), context.c_str());
742 
743  return false;
744  }
745  return true;
746 }
747 
749 {
750  int nArgs = 0;
751  if (const config& args = cfg.child("args")) {
752  luaW_pushconfig(this->mState, args);
753  ++nArgs;
754  }
755  this->run(cfg["code"].str().c_str(), nArgs);
756 }
757 // Call load_string and protected call. Make them throw exceptions.
758 //
759 void lua_kernel_base::throwing_run(const char * prog, int nArgs)
760 {
761  cmd_log_ << "$ " << prog << "\n";
762  error_handler eh = std::bind(&lua_kernel_base::throw_exception, this, _1, _2 );
763  this->load_string(prog, eh);
764  lua_insert(mState, -nArgs - 1);
765  this->protected_call(nArgs, 0, eh);
766 }
767 
768 // Do a throwing run, but if we catch a lua_error, reformat it with signature for this function and log it.
769 void lua_kernel_base::run(const char * prog, int nArgs)
770 {
771  try {
772  this->throwing_run(prog, nArgs);
773  } catch (const game::lua_error & e) {
774  cmd_log_ << e.what() << "\n";
775  lua_kernel_base::log_error(e.what(), "In function lua_kernel::run()");
776  }
777 }
778 
779 // Tests if a program resolves to an expression, and pretty prints it if it is, otherwise it runs it normally. Throws exceptions.
780 void lua_kernel_base::interactive_run(char const * prog) {
781  std::string experiment = "ilua._pretty_print(";
782  experiment += prog;
783  experiment += ")";
784 
785  error_handler eh = std::bind(&lua_kernel_base::throw_exception, this, _1, _2 );
786 
787  try {
788  // Try to load the experiment without syntax errors
789  this->load_string(experiment.c_str(), eh);
790  } catch (const game::lua_error &) {
791  this->throwing_run(prog, 0); // Since it failed, fall back to the usual throwing_run, on the original input.
792  return;
793  }
794  // experiment succeeded, now run but log normally.
795  cmd_log_ << "$ " << prog << "\n";
796  this->protected_call(0, 0, eh);
797 }
798 /**
799  * Loads and executes a Lua file.
800  * - Arg 1: string containing the file name.
801  * - Ret *: values returned by executing the file body.
802  */
804 {
805  luaL_checkstring(L, 1);
806  lua_rotate(L, 1, -1);
807  if (lua_fileops::load_file(L) != 1) return 0;
808  //^ should end with the file contents loaded on the stack. actually it will call lua_error otherwise, the return 0 is redundant.
809  lua_rotate(L, 1, 1);
810  // Using a non-protected call here appears to fix an issue in plugins.
811  // The protected call isn't technically necessary anyway, because this function is called from Lua code,
812  // which should already be in a protected environment.
813  lua_call(L, lua_gettop(L) - 1, LUA_MULTRET);
814  return lua_gettop(L);
815 }
816 
817 /**
818  * Loads and executes a Lua file, if there is no corresponding entry in wesnoth.package.
819  * Stores the result of the script in wesnoth.package and returns it.
820  * - Arg 1: string containing the file name.
821  * - Ret 1: value returned by the script.
822  */
824 {
825  const char * m = luaL_checkstring(L, 1);
826  if(!m) {
827  return luaL_argerror(L, 1, "found a null string argument to wesnoth require");
828  }
829 
830  // Check if there is already an entry.
831 
832  lua_getglobal(L, "wesnoth");
833  lua_pushstring(L, "package");
834  lua_rawget(L, -2);
835  lua_pushvalue(L, 1);
836  lua_rawget(L, -2);
837  if(!lua_isnil(L, -1) && !game_config::debug_lua) {
838  return 1;
839  }
840  lua_pop(L, 1);
841  lua_pushvalue(L, 1);
842  // stack is now [packagename] [wesnoth] [package] [packagename]
843 
844  if(lua_fileops::load_file(L) != 1) {
845  // should end with the file contents loaded on the stack. actually it will call lua_error otherwise, the return 0 is redundant.
846  // stack is now [packagename] [wesnoth] [package] [chunk]
847  return 0;
848  }
849  DBG_LUA << "require: loaded a file, now calling it\n";
850 
851  if (!this->protected_call(L, 0, 1, std::bind(&lua_kernel_base::log_error, this, _1, _2))) {
852  // historically if wesnoth.require fails it just yields nil and some logging messages, not a lua error
853  return 0;
854  }
855  // stack is now [packagename] [wesnoth] [package] [results]
856 
857  lua_pushvalue(L, 1);
858  lua_pushvalue(L, -2);
859  // stack is now [packagename] [wesnoth] [package] [results] [packagename] [results]
860  // Add the return value to the table.
861 
862  lua_settable(L, -4);
863  // stack is now [packagename] [wesnoth] [package] [results]
864  return 1;
865 }
867 {
868  lua_push(L, my_name());
869  return 1;
870 }
872 {
873  char const *m = luaL_checkstring(L, 2);
885  return 0;
886 }
888 {
889  std::string err_msg = "unknown modifiable property of game_config: ";
890  err_msg += luaL_checkstring(L, 2);
891  return luaL_argerror(L, 2, err_msg.c_str());
892 }
893 /**
894  * Loads the "package" package into the Lua environment.
895  * This action is inherently unsafe, as Lua scripts will now be able to
896  * load C libraries on their own, hence granting them the same privileges
897  * as the Wesnoth binary itself.
898  */
900 {
901  lua_State *L = mState;
903  lua_pushstring(L, "package");
904  lua_call(L, 1, 0);
905 }
906 
908 {
909  lua_State* L = mState;
910  lua_settop(L, 0);
911  cmd_log_ << "Loading core...\n";
912  luaW_getglobal(L, "wesnoth", "require");
913  lua_pushstring(L, "lua/core.lua");
914  if(!protected_call(1, 1)) {
915  cmd_log_ << "Error: Failed to load core.\n";
916  }
917  lua_settop(L, 0);
918 }
919 
920 /**
921  * Gets all the global variable names in the Lua environment. This is useful for tab completion.
922  */
923 std::vector<std::string> lua_kernel_base::get_global_var_names()
924 {
925  std::vector<std::string> ret;
926 
927  lua_State *L = mState;
928 
929  int idx = lua_gettop(L);
930  lua_getglobal(L, "_G");
931  lua_pushnil(L);
932 
933  while (lua_next(L, idx+1) != 0) {
934  if (lua_isstring(L, -2)) {
935  ret.push_back(lua_tostring(L,-2));
936  }
937  lua_pop(L,1);
938  }
939  lua_settop(L, idx);
940  return ret;
941 }
942 
943 /**
944  * Gets all attribute names of an extended variable name. This is useful for tab completion.
945  */
946 std::vector<std::string> lua_kernel_base::get_attribute_names(const std::string & input)
947 {
948  std::vector<std::string> ret;
949  std::string base_path = input;
950  std::size_t last_dot = base_path.find_last_of('.');
951  std::string partial_name = base_path.substr(last_dot + 1);
952  base_path.erase(last_dot);
953  std::string load = "return " + base_path;
954 
955  lua_State* L = mState;
956  int save_stack = lua_gettop(L);
957  int result = luaL_loadstring(L, load.c_str());
958  if(result != LUA_OK) {
959  // 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.
960  LOG_LUA << "Error when attempting tab completion:\n";
961  LOG_LUA << luaL_checkstring(L, -1) << '\n';
962  // Just return an empty list; no matches were found
963  lua_settop(L, save_stack);
964  return ret;
965  }
966 
967  luaW_pcall(L, 0, 1);
968  if(lua_istable(L, -1) || lua_isuserdata(L, -1)) {
969  int top = lua_gettop(L);
970  int obj = lua_absindex(L, -1);
971  if(luaL_getmetafield(L, obj, "__tab_enum") == LUA_TFUNCTION) {
972  lua_pushvalue(L, obj);
973  lua_pushlstring(L, partial_name.c_str(), partial_name.size());
974  luaW_pcall(L, 2, 1);
975  ret = lua_check<std::vector<std::string>>(L, -1);
976  } else if(lua_type(L, -1) != LUA_TTABLE) {
977  LOG_LUA << "Userdata missing __tab_enum meta-function for tab completion";
978  lua_settop(L, save_stack);
979  return ret;
980  } else {
981  lua_settop(L, top);
982  // Metafunction not found, so use lua_next to enumerate the table
983  for(lua_pushnil(L); lua_next(L, obj); lua_pop(L, 1)) {
984  if(lua_type(L, -2) == LUA_TSTRING) {
985  std::string attr = lua_tostring(L, -2);
986  if(attr.empty()) {
987  continue;
988  }
989  if(!isalpha(attr[0]) && attr[0] != '_') {
990  continue;
991  }
992  if(std::any_of(attr.begin(), attr.end(), [](char c){
993  return !isalpha(c) && !isdigit(c) && c != '_';
994  })) {
995  continue;
996  }
997  if(attr.substr(0, partial_name.size()) == partial_name) {
998  ret.push_back(base_path + "." + attr);
999  }
1000  }
1001  }
1002  }
1003  }
1004  lua_settop(L, save_stack);
1005  return ret;
1006 }
1007 
1009 {
1010  #ifdef __GNUC__
1011  #pragma GCC diagnostic push
1012  #pragma GCC diagnostic ignored "-Wold-style-cast"
1013  #endif
1014  return *reinterpret_cast<lua_kernel_base**>(lua_getextraspace(L));
1015  #ifdef __GNUC__
1016  #pragma GCC diagnostic pop
1017  #endif
1018 }
1019 
1021 {
1022  return seed_rng::next_seed();
1023 }
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:824
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:947
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:889
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:423
bool matches(const config &filter) const
Definition: config.cpp:1182
std::string register_tstring_metatable(lua_State *L)
Adds the tstring metatable.
Definition: lua_common.cpp:419
std::string format_conjunct_list(const t_string &empty, const std::vector< t_string > &elems)
Format a conjunctive list.
int intf_add_dialog_tree_node(lua_State *L)
Sets a widget&#39;s state to active or inactive.
Definition: lua_gui2.cpp:908
int intf_read_file(lua_State *L)
Reads a file into a string, or a directory into a list of files therein.
std::string interpolate_variables_into_string(const std::string &str, const string_map *const symbols)
Function which will interpolate variables, starting with &#39;$&#39; in the string &#39;str&#39; with the equivalent ...
LUALIB_API lua_State * luaL_newstate(void)
Definition: lauxlib.cpp:1026
LUAMOD_API int luaopen_debug(lua_State *L)
Definition: ldblib.cpp:452
int show_story(lua_State *L)
Displays a story screen.
Definition: lua_gui2.cpp:367
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:712
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.
Definition: lua_common.cpp:982
static int intf_format(lua_State *L)
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
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
static int intf_format_list(lua_State *L)
int show_dialog(lua_State *L)
Displays a window.
Definition: lua_gui2.cpp:233
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:210
int intf_textdomain(lua_State *L)
Creates an interface for gettext.
Definition: lua_common.cpp:83
#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
std::string format_disjunct_list(const t_string &empty, const std::vector< t_string > &elems)
Format a disjunctive list.
#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:108
#define LUA_TFUNCTION
Definition: lua.h:70
LUA_API int lua_isuserdata(lua_State *L, int idx)
Definition: lapi.cpp:289
int show_message_dialog(lua_State *L)
Displays a message window.
Definition: lua_gui2.cpp:264
int intf_remove_dialog_item(lua_State *L)
Removes an entry from a list.
Definition: lua_gui2.cpp:661
void lua_push(lua_State *L, const T &val)
Definition: push_check.hpp:293
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:770
#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)
LUA_API int lua_absindex(lua_State *L, int idx)
Definition: lapi.cpp:160
int intf_add_widget_definition(lua_State *L)
Definition: lua_gui2.cpp:933
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:60
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:812
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:219
void load_core()
Loads the "core" library into the Lua environment.
void throwing_run(char const *prog, int nArgs)
Runs a plain script, but reports errors by throwing lua_error.
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:851
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
const t_string name
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:602
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)
#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
LUA_API int lua_setmetatable(lua_State *L, int objindex)
Definition: lapi.cpp:846
int show_menu(lua_State *L)
Displays a popup menu at the current mouse position Best used from a [set_menu_item], to show a submenu.
Definition: lua_gui2.cpp:380
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:789
int luaW_pcall_internal(lua_State *L, int nArgs, int nRets)
Definition: lua_common.cpp:959
#define lua_newtable(L)
Definition: lua.h:346
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
bool load_string(char const *prog, error_handler)
void run(char const *prog, int nArgs=0)
Runs a plain script.
virtual int impl_game_config_get(lua_State *L)
#define LUA_ERRGCMM
Definition: lua.h:52
int show_popup_dialog(lua_State *L)
Displays a popup message.
Definition: lua_gui2.cpp:353
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
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:443
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:400
config luaW_checkconfig(lua_State *L, int index)
Converts an optional table or vconfig to a config object.
Definition: lua_common.cpp:799
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
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_debug(lua_State *L)
Dumps a wml table or userdata wml object into a pretty string.
static int intf_compare_versions(lua_State *L)
Compares 2 version strings - which is newer.
LUA_API void lua_rotate(lua_State *L, int idx, int n)
Definition: lapi.cpp:207
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
#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:719
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 return_bool_attrib(name, accessor)
Definition: lua_common.hpp:235
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")
static int intf_wml_matches_filter(lua_State *L)
#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:570
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)
Definition: lua_common.cpp:953
int show_message_box(lua_State *L)
Displays a simple message box.
Definition: lua_gui2.cpp:406
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
int intf_tovconfig(lua_State *L)
Creates a vconfig containing the WML table.
Definition: lua_common.cpp:390
lua_State * mState
static int intf_load(lua_State *L)
Replacement load function.
t_string interpolate_variables_into_tstring(const t_string &tstr, const variable_set &variables)
Function that does the same as the above, for t_stringS.
#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:790
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:842
LUA_API int lua_next(lua_State *L, int idx)
Definition: lapi.cpp:1123
std::string debug() const
Definition: config.cpp:1230
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