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