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"
45 #include "serialization/parser.hpp"
47 #include "utils/functional.hpp"
48 #include "utils/name_generator.hpp"
51 #include "variable.hpp" // for config_variable_set
52 
53 #include <cstring>
54 #include <exception>
55 #include <new>
56 #include <string>
57 #include <sstream>
58 #include <vector>
59 #include <fstream>
60 
61 #include "lua/lauxlib.h"
62 #include "lua/lua.h"
63 #include "lua/lualib.h"
64 
65 static lg::log_domain log_scripting_lua("scripting/lua");
66 static lg::log_domain log_user("scripting/lua/user");
67 #define DBG_LUA LOG_STREAM(debug, log_scripting_lua)
68 #define LOG_LUA LOG_STREAM(info, log_scripting_lua)
69 #define WRN_LUA LOG_STREAM(warn, log_scripting_lua)
70 #define ERR_LUA LOG_STREAM(err, log_scripting_lua)
71 
72 // Registry key for metatable
73 static const char * Gen = "name generator";
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 
288 {
289  config cfg = luaW_checkconfig(L, 1);
290  config filter = luaW_checkconfig(L, 2);
291  lua_pushboolean(L, cfg.matches(filter));
292  return 1;
293 }
294 
295 /**
296 * Logs a message
297 * Arg 1: (optional) Logger
298 * Arg 2: Message
299 */
300 static int intf_log(lua_State *L) {
301  const std::string& logger = lua_isstring(L, 2) ? luaL_checkstring(L, 1) : "";
302  std::string msg = lua_isstring(L, 2) ? luaL_checkstring(L, 2) : luaL_checkstring(L, 1);
303  if(msg.empty() || msg.back() != '\n') {
304  msg += '\n';
305  }
306 
307  if(logger == "err" || logger == "error") {
308  LOG_STREAM(err, log_user) << msg;
309  } else if(logger == "warn" || logger == "wrn" || logger == "warning") {
311  } else if((logger == "debug" || logger == "dbg")) {
313  } else {
315  }
316  return 0;
317 }
318 
319 /**
320  * Logs a deprecation message. See deprecation.cpp for details
321  * Arg 1: Element to be deprecated.
322  * Arg 2: Deprecation level.
323  * Arg 3: Version when element may be removed.
324  * Arg 4: Additional detail message.
325  */
327  const std::string elem = luaL_checkstring(L, 1);
328  // This could produce an invalid deprecation level, but that possibility is handled in deprecated_message()
330  const std::string ver_str = lua_isnoneornil(L, 3) ? "" : luaL_checkstring(L, 3);
331  const std::string detail = luaW_checktstring(L, 4);
332  const version_info ver = ver_str.empty() ? game_config::wesnoth_version.str() : ver_str;
333  const std::string msg = deprecated_message(elem, level, ver, detail);
334  if(level < DEP_LEVEL::INDEFINITE || level >= DEP_LEVEL::REMOVED) {
335  // Invalid deprecation level or level 4 deprecation should raise an interpreter error
336  lua_push(L, msg);
337  return lua_error(L);
338  }
339  return 0;
340 }
341 
342 /**
343 * Gets the dimension of an image.
344 * - Arg 1: string.
345 * - Ret 1: width.
346 * - Ret 2: height.
347 */
349  char const *m = luaL_checkstring(L, 1);
350  image::locator img(m);
351  if(!img.file_exists()) return 0;
352  surface s = get_image(img);
353  lua_pushinteger(L, s->w);
354  lua_pushinteger(L, s->h);
355  return 2;
356 }
357 
358 /**
359 * Returns the time stamp, exactly as [set_variable] time=stamp does.
360 * - Ret 1: integer
361 */
363  lua_pushinteger(L, SDL_GetTicks());
364  return 1;
365 }
366 
367 static int intf_format(lua_State* L)
368 {
369  config cfg = luaW_checkconfig(L, 2);
370  config_variable_set variables(cfg);
371  if(lua_isstring(L, 1)) {
372  std::string str = lua_tostring(L, 1);
374  return 1;
375  }
376  t_string str = luaW_checktstring(L, 1);
378  return 1;
379 }
380 
381 template<bool conjunct>
383 {
384  const t_string empty = luaW_checktstring(L, 1);
385  auto values = lua_check<std::vector<t_string>>(L, 2);
386  lua_push(L, (conjunct ? utils::format_conjunct_list : utils::format_disjunct_list)(empty, values));
387  return 1;
388 }
389 
390 /**
391 * Dumps a wml table or userdata wml object into a pretty string.
392 * - Arg 1: wml table or vconfig userdata
393 * - Ret 1: string
394 */
395 static int intf_wml_tostring(lua_State* L) {
396  const config& arg = luaW_checkconfig(L, 1);
397  std::ostringstream stream;
398  write(stream, arg);
399  lua_pushstring(L, stream.str().c_str());
400  return 1;
401 }
402 
403 /**
404  * Loads a WML file into a config
405  * - Arg 1: WML file path
406  * - Arg 2: (optional) Array of preprocessor defines, or false to skip preprocessing (true is also valid)
407  * - Arg 3: (optional) Path to a schema file for validation (omit for no validation)
408  * - Ret: config
409  */
410 static int intf_load_wml(lua_State* L)
411 {
412  std::string file = luaL_checkstring(L, 1);
413  bool preprocess = true;
414  preproc_map defines_map;
415  if(lua_type(L, 2) == LUA_TBOOLEAN) {
416  preprocess = luaW_toboolean(L, 2);
417  } else if(lua_type(L, 2) == LUA_TTABLE || lua_type(L, 2) == LUA_TUSERDATA) {
418  lua_len(L, 2);
419  int n = lua_tonumber(L, -1);
420  lua_pop(L, 1);
421  for(int i = 0; i < n; i++) {
422  lua_geti(L, 2, i);
423  if(!lua_isstring(L, -1)) {
424  return luaL_argerror(L, 2, "expected bool or array of strings");
425  }
426  std::string define = lua_tostring(L, -1);
427  lua_pop(L, 1);
428  if(!define.empty()) {
429  defines_map.emplace(define, preproc_define(define));
430  }
431  }
432  } else if(!lua_isnoneornil(L, 2)) {
433  return luaL_argerror(L, 2, "expected bool or array of strings");
434  }
435  std::string schema_path = luaL_optstring(L, 3, "");
436  std::shared_ptr<schema_validation::schema_validator> validator;
437  if(!schema_path.empty()) {
438  validator.reset(new schema_validation::schema_validator(filesystem::get_wml_location(schema_path)));
439  validator->set_create_exceptions(false); // Don't crash if there's an error, just go ahead anyway
440  }
441  std::string wml_file = filesystem::get_wml_location(file);
443  config result;
444  if(preprocess) {
445  stream = preprocess_file(wml_file, &defines_map);
446  } else {
447  stream.reset(new std::ifstream(wml_file));
448  }
449  read(result, *stream, validator.get());
450  luaW_pushconfig(L, result);
451  return 1;
452 }
453 
454 /**
455  * Parses a WML string into a config; does not preprocess or validate
456  * - Arg 1: WML string
457  * - Ret: config
458  */
459 static int intf_parse_wml(lua_State* L)
460 {
461  std::string wml = luaL_checkstring(L, 1);
462  std::string schema_path = luaL_optstring(L, 2, "");
463  std::shared_ptr<schema_validation::schema_validator> validator;
464  if(!schema_path.empty()) {
465  validator.reset(new schema_validation::schema_validator(filesystem::get_wml_location(schema_path)));
466  validator->set_create_exceptions(false); // Don't crash if there's an error, just go ahead anyway
467  }
468  config result;
469  read(result, wml, validator.get());
470  luaW_pushconfig(L, result);
471  return 1;
472 }
473 
474 /**
475  * Returns a clone (deep copy) of the passed config, which can be either a normal config or a vconfig
476  * If it is a vconfig, the underlying config is also cloned.
477  * - Arg 1: a config
478  * - Ret: the cloned config
479  */
480 static int intf_clone_wml(lua_State* L)
481 {
482  const vconfig* vcfg = nullptr;
483  const config& cfg = luaW_checkconfig(L, 1, vcfg);
484  if(vcfg) {
485  config clone_underlying = vcfg->get_config();
486  vconfig clone(clone_underlying);
487  luaW_pushvconfig(L, clone);
488  } else {
489  luaW_pushconfig(L, cfg);
490  }
491  return 1;
492 }
493 
494 // End Callback implementations
495 
496 // Template which allows to push member functions to the lua kernel base into lua as C functions, using a shim
498 
499 template <member_callback method>
501  return ((lua_kernel_base::get_lua_kernel<lua_kernel_base>(L)).*method)(L);
502 }
503 
504 // Ctor, initialization
506  : mState(luaL_newstate())
507  , cmd_log_()
508 {
510  lua_State *L = mState;
511 
512  cmd_log_ << "Initializing " << my_name() << "...\n";
513 
514  // Open safe libraries.
515  // Debug and OS are not, but most of their functions will be disabled below.
516  cmd_log_ << "Adding standard libs...\n";
517 
518  static const luaL_Reg safe_libs[] {
519  { "", luaopen_base },
520  { "table", luaopen_table },
521  { "string", luaopen_string },
522  { "math", luaopen_math },
523  { "coroutine", luaopen_coroutine },
524  { "debug", luaopen_debug },
525  { "os", luaopen_os },
526  { "utf8", luaopen_utf8 }, // added in Lua 5.3
527  { nullptr, nullptr }
528  };
529  for (luaL_Reg const *lib = safe_libs; lib->func; ++lib)
530  {
531  luaL_requiref(L, lib->name, lib->func, 1);
532  lua_pop(L, 1); /* remove lib */
533  }
534 
535  // Disable functions from os which we don't want.
536  lua_getglobal(L, "os");
537  lua_pushnil(L);
538  while(lua_next(L, -2) != 0) {
539  lua_pop(L, 1);
540  char const* function = lua_tostring(L, -1);
541  if(strcmp(function, "clock") == 0 || strcmp(function, "date") == 0
542  || strcmp(function, "time") == 0 || strcmp(function, "difftime") == 0) continue;
543  lua_pushnil(L);
544  lua_setfield(L, -3, function);
545  }
546  lua_pop(L, 1);
547 
548  // Disable functions from debug which we don't want.
549  lua_getglobal(L, "debug");
550  lua_pushnil(L);
551  while(lua_next(L, -2) != 0) {
552  lua_pop(L, 1);
553  char const* function = lua_tostring(L, -1);
554  if(strcmp(function, "traceback") == 0 || strcmp(function, "getinfo") == 0) continue; //traceback is needed for our error handler
555  lua_pushnil(L); //getinfo is needed for ilua strict mode
556  lua_setfield(L, -3, function);
557  }
558  lua_pop(L, 1);
559 
560  // Delete dofile and loadfile.
561  lua_pushnil(L);
562  lua_setglobal(L, "dofile");
563  lua_pushnil(L);
564  lua_setglobal(L, "loadfile");
565 
566  // Store the error handler.
567  cmd_log_ << "Adding error handler...\n";
569 
570  // Create the gettext metatable.
572 
573  // Create the tstring metatable.
575 
576 
577  lua_settop(L, 0);
578 
579  // Define the CPP_function metatable ( so we can override print to point to a C++ member function, add "show_dialog" for this kernel, etc. )
580  cmd_log_ << "Adding boost function proxy...\n";
581 
583 
584  // Add some callback from the wesnoth lib
585  cmd_log_ << "Registering basic wesnoth API...\n";
586 
587  static luaL_Reg const callbacks[] {
588  { "compare_versions", &intf_compare_versions },
589  { "debug", &intf_wml_tostring },
590  { "deprecated_message", &intf_deprecated_message },
591  { "have_file", &lua_fileops::intf_have_file },
592  { "read_file", &lua_fileops::intf_read_file },
593  { "textdomain", &lua_common::intf_textdomain },
594  { "tovconfig", &lua_common::intf_tovconfig },
595  { "get_dialog_value", &lua_gui2::intf_get_dialog_value },
596  { "set_dialog_tooltip", &lua_gui2::intf_set_dialog_tooltip },
597  { "set_dialog_active", &lua_gui2::intf_set_dialog_active },
598  { "set_dialog_visible", &lua_gui2::intf_set_dialog_visible },
599  { "add_dialog_tree_node", &lua_gui2::intf_add_dialog_tree_node },
600  { "add_widget_definition", &lua_gui2::intf_add_widget_definition },
601  { "set_dialog_callback", &lua_gui2::intf_set_dialog_callback },
602  { "set_dialog_canvas", &lua_gui2::intf_set_dialog_canvas },
603  { "set_dialog_focus", &lua_gui2::intf_set_dialog_focus },
604  { "set_dialog_markup", &lua_gui2::intf_set_dialog_markup },
605  { "set_dialog_value", &lua_gui2::intf_set_dialog_value },
606  { "remove_dialog_item", &lua_gui2::intf_remove_dialog_item },
607  { "dofile", &dispatch<&lua_kernel_base::intf_dofile> },
608  { "require", &dispatch<&lua_kernel_base::intf_require> },
609  { "kernel_type", &dispatch<&lua_kernel_base::intf_kernel_type> },
610  { "show_dialog", &lua_gui2::show_dialog },
611  { "show_menu", &lua_gui2::show_menu },
612  { "show_message_dialog", &lua_gui2::show_message_dialog },
613  { "show_popup_dialog", &lua_gui2::show_popup_dialog },
614  { "show_story", &lua_gui2::show_story },
615  { "show_message_box", &lua_gui2::show_message_box },
616  { "show_lua_console", &dispatch<&lua_kernel_base::intf_show_lua_console> },
617  { "compile_formula", &lua_formula_bridge::intf_compile_formula},
618  { "eval_formula", &lua_formula_bridge::intf_eval_formula},
619  { "name_generator", &intf_name_generator },
620  { "random", &intf_random },
621  { "wml_matches_filter", &intf_wml_matches_filter },
622  { "log", &intf_log },
623  { "get_image_size", &intf_get_image_size },
624  { "get_time_stamp", &intf_get_time_stamp },
625  { "format", &intf_format },
626  { "format_conjunct_list", &intf_format_list<true> },
627  { "format_disjunct_list", &intf_format_list<false> },
628  { nullptr, nullptr }
629  };
630 
631  lua_getglobal(L, "wesnoth");
632  if (!lua_istable(L,-1)) {
633  lua_newtable(L);
634  }
635  luaL_setfuncs(L, callbacks, 0);
636  //lua_cpp::set_functions(L, cpp_callbacks, 0);
637  lua_setglobal(L, "wesnoth");
638 
639  static luaL_Reg const wml_callbacks[]= {
640  { "load", &intf_load_wml},
641  { "parse", &intf_parse_wml},
642  { "clone", &intf_clone_wml},
643  { nullptr, nullptr },
644  };
645  lua_newtable(L);
646  luaL_setfuncs(L, wml_callbacks, 0);
647  lua_setglobal(L, "wml");
648 
649  // Override the print function
650  cmd_log_ << "Redirecting print function...\n";
651 
652  lua_getglobal(L, "print");
653  lua_setglobal(L, "std_print"); //storing original impl as 'std_print'
654  lua_settop(L, 0); //clear stack, just to be sure
655 
656  lua_pushcfunction(L, &dispatch<&lua_kernel_base::intf_print>);
657  lua_setglobal(L, "print");
658 
660  lua_setglobal(L, "load");
661  lua_pushnil(L);
662  lua_setglobal(L, "loadstring");
663 
664  cmd_log_ << "Initializing package repository...\n";
665  // Create the package table.
666  lua_getglobal(L, "wesnoth");
667  lua_newtable(L);
668  lua_setfield(L, -2, "package");
669  lua_pop(L, 1);
670  lua_settop(L, 0);
671  lua_pushstring(L, "lua/package.lua");
672  int res = intf_require(L);
673  if(res != 1) {
674  cmd_log_ << "Error: Failed to initialize package repository. Falling back to less flexible C++ implementation.\n";
675  }
676 
677  // Get some callbacks for map locations
678  cmd_log_ << "Adding map table...\n";
679 
680  static luaL_Reg const map_callbacks[] {
681  { "get_direction", &lua_map_location::intf_get_direction },
682  { "vector_sum", &lua_map_location::intf_vector_sum },
683  { "vector_diff", &lua_map_location::intf_vector_diff },
684  { "vector_negation", &lua_map_location::intf_vector_negation },
685  { "rotate_right_around_center", &lua_map_location::intf_rotate_right_around_center },
686  { "tiles_adjacent", &lua_map_location::intf_tiles_adjacent },
687  { "get_adjacent_tiles", &lua_map_location::intf_get_adjacent_tiles },
688  { "distance_between", &lua_map_location::intf_distance_between },
689  { "get_in_basis_N_NE", &lua_map_location::intf_get_in_basis_N_NE },
690  { "get_relative_dir", &lua_map_location::intf_get_relative_dir },
691  { nullptr, nullptr }
692  };
693 
694  // Create the map_location table.
695  lua_getglobal(L, "wesnoth");
696  lua_newtable(L);
697  luaL_setfuncs(L, map_callbacks, 0);
698  lua_setfield(L, -2, "map");
699  lua_pop(L, 1);
700 
701  // Create the game_config variable with its metatable.
702  cmd_log_ << "Adding game_config table...\n";
703 
704  lua_getglobal(L, "wesnoth");
705  lua_newuserdata(L, 0);
706  lua_createtable(L, 0, 3);
707  lua_pushcfunction(L, &dispatch<&lua_kernel_base::impl_game_config_get>);
708  lua_setfield(L, -2, "__index");
709  lua_pushcfunction(L, &dispatch<&lua_kernel_base::impl_game_config_set>);
710  lua_setfield(L, -2, "__newindex");
711  lua_pushstring(L, "game config");
712  lua_setfield(L, -2, "__metatable");
713  lua_setmetatable(L, -2);
714  lua_setfield(L, -2, "game_config");
715  lua_pop(L, 1);
716 
717  // Add mersenne twister rng wrapper
718  cmd_log_ << "Adding rng tables...\n";
720 
721  cmd_log_ << "Adding name generator metatable...\n";
723  static luaL_Reg const generator[] {
724  { "__call", &impl_name_generator_call},
725  { "__gc", &impl_name_generator_collect},
726  { nullptr, nullptr}
727  };
728  luaL_setfuncs(L, generator, 0);
729 
730  // Create formula bridge metatables
732 
733  // Loading ilua:
734  cmd_log_ << "Loading ilua...\n";
735 
736  lua_settop(L, 0);
737  luaW_getglobal(L, "wesnoth", "require");
738  lua_pushstring(L, "lua/ilua.lua");
739  if(protected_call(1, 1)) {
740  //run "ilua.set_strict()"
741  lua_pushstring(L, "set_strict");
742  lua_gettable(L, -2);
743  if (!this->protected_call(0,0, std::bind(&lua_kernel_base::log_error, this, _1, _2))) {
744  cmd_log_ << "Failed to activate strict mode.\n";
745  } else {
746  cmd_log_ << "Activated strict mode.\n";
747  }
748 
749  lua_setglobal(L, "ilua"); //save ilua table as a global
750  } else {
751  cmd_log_ << "Error: failed to load ilua.\n";
752  }
753  lua_settop(L, 0);
754 }
755 
757 {
758  for (const auto& pair : this->registered_widget_definitions_) {
759  gui2::remove_single_widget_definition(std::get<0>(pair), std::get<1>(pair));
760  }
761  lua_close(mState);
762 }
763 
764 void lua_kernel_base::log_error(char const * msg, char const * context)
765 {
766  ERR_LUA << context << ": " << msg << '\n';
767 }
768 
769 void lua_kernel_base::throw_exception(char const * msg, char const * context)
770 {
771  throw game::lua_error(msg, context);
772 }
773 
774 bool lua_kernel_base::protected_call(int nArgs, int nRets)
775 {
776  error_handler eh = std::bind(&lua_kernel_base::log_error, this, _1, _2 );
777  return this->protected_call(nArgs, nRets, eh);
778 }
779 
780 bool lua_kernel_base::load_string(char const * prog, const std::string& name)
781 {
782  error_handler eh = std::bind(&lua_kernel_base::log_error, this, _1, _2 );
783  return this->load_string(prog, name, eh);
784 }
785 
786 bool lua_kernel_base::protected_call(int nArgs, int nRets, error_handler e_h)
787 {
788  return this->protected_call(mState, nArgs, nRets, e_h);
789 }
790 
791 bool lua_kernel_base::protected_call(lua_State * L, int nArgs, int nRets, error_handler e_h)
792 {
793  int errcode = luaW_pcall_internal(L, nArgs, nRets);
794 
795  if (errcode != LUA_OK) {
796  char const * msg = lua_tostring(L, -1);
797 
798  std::string context = "When executing, ";
799  if (errcode == LUA_ERRRUN) {
800  context += "Lua runtime error: ";
801  } else if (errcode == LUA_ERRERR) {
802  context += "Lua error in attached debugger: ";
803  } else if (errcode == LUA_ERRMEM) {
804  context += "Lua out of memory error: ";
805  } else if (errcode == LUA_ERRGCMM) {
806  context += "Lua error in garbage collection metamethod: ";
807  } else {
808  context += "unknown lua error: ";
809  }
810  if(lua_isstring(L, -1)) {
811  context += msg ? msg : "null string";
812  } else {
813  context += lua_typename(L, lua_type(L, -1));
814  }
815 
816  lua_pop(L, 1);
817 
818  e_h(context.c_str(), "Lua Error");
819 
820  return false;
821  }
822 
823  return true;
824 }
825 
826 bool lua_kernel_base::load_string(char const * prog, const std::string& name, error_handler e_h)
827 {
828  // pass 't' to prevent loading bytecode which is unsafe and can be used to escape the sandbox.
829  // todo: maybe allow a 'name' parameter to give better error messages.
830  int errcode = luaL_loadbufferx(mState, prog, strlen(prog), name.empty() ? name.c_str() : prog, "t");
831  if (errcode != LUA_OK) {
832  char const * msg = lua_tostring(mState, -1);
833  std::string message = msg ? msg : "null string";
834 
835  std::string context = "When parsing a string to lua, ";
836 
837  if (errcode == LUA_ERRSYNTAX) {
838  context += " a syntax error";
839  } else if(errcode == LUA_ERRMEM){
840  context += " a memory error";
841  } else if(errcode == LUA_ERRGCMM) {
842  context += " an error in garbage collection metamethod";
843  } else {
844  context += " an unknown error";
845  }
846 
847  lua_pop(mState, 1);
848 
849  e_h(message.c_str(), context.c_str());
850 
851  return false;
852  }
853  return true;
854 }
855 
857 {
858  int nArgs = 0;
859  if (const config& args = cfg.child("args")) {
860  luaW_pushconfig(this->mState, args);
861  ++nArgs;
862  }
863  this->run(cfg["code"].str().c_str(), cfg["name"].str(), nArgs);
864 }
865 // Call load_string and protected call. Make them throw exceptions.
866 //
867 void lua_kernel_base::throwing_run(const char * prog, const std::string& name, int nArgs)
868 {
869  cmd_log_ << "$ " << prog << "\n";
870  error_handler eh = std::bind(&lua_kernel_base::throw_exception, this, _1, _2 );
871  this->load_string(prog, name, eh);
872  lua_insert(mState, -nArgs - 1);
873  this->protected_call(nArgs, 0, eh);
874 }
875 
876 // Do a throwing run, but if we catch a lua_error, reformat it with signature for this function and log it.
877 void lua_kernel_base::run(const char * prog, const std::string& name, int nArgs)
878 {
879  try {
880  this->throwing_run(prog, name, nArgs);
881  } catch (const game::lua_error & e) {
882  cmd_log_ << e.what() << "\n";
883  lua_kernel_base::log_error(e.what(), "In function lua_kernel::run()");
884  }
885 }
886 
887 // Tests if a program resolves to an expression, and pretty prints it if it is, otherwise it runs it normally. Throws exceptions.
888 void lua_kernel_base::interactive_run(char const * prog) {
889  std::string experiment = "ilua._pretty_print(";
890  experiment += prog;
891  experiment += ")";
892 
893  error_handler eh = std::bind(&lua_kernel_base::throw_exception, this, _1, _2 );
894 
895  try {
896  // Try to load the experiment without syntax errors
897  this->load_string(experiment.c_str(), "interactive", eh);
898  } catch (const game::lua_error &) {
899  this->throwing_run(prog, "interactive", 0); // Since it failed, fall back to the usual throwing_run, on the original input.
900  return;
901  }
902  // experiment succeeded, now run but log normally.
903  cmd_log_ << "$ " << prog << "\n";
904  this->protected_call(0, 0, eh);
905 }
906 /**
907  * Loads and executes a Lua file.
908  * - Arg 1: string containing the file name.
909  * - Ret *: values returned by executing the file body.
910  */
912 {
913  luaL_checkstring(L, 1);
914  lua_rotate(L, 1, -1);
915  if (lua_fileops::load_file(L) != 1) return 0;
916  //^ should end with the file contents loaded on the stack. actually it will call lua_error otherwise, the return 0 is redundant.
917  lua_rotate(L, 1, 1);
918  // Using a non-protected call here appears to fix an issue in plugins.
919  // The protected call isn't technically necessary anyway, because this function is called from Lua code,
920  // which should already be in a protected environment.
921  lua_call(L, lua_gettop(L) - 1, LUA_MULTRET);
922  return lua_gettop(L);
923 }
924 
925 /**
926  * Loads and executes a Lua file, if there is no corresponding entry in wesnoth.package.
927  * Stores the result of the script in wesnoth.package and returns it.
928  * - Arg 1: string containing the file name.
929  * - Ret 1: value returned by the script.
930  */
932 {
933  const char * m = luaL_checkstring(L, 1);
934  if(!m) {
935  return luaL_argerror(L, 1, "found a null string argument to wesnoth require");
936  }
937 
938  // Check if there is already an entry.
939 
940  lua_getglobal(L, "wesnoth");
941  lua_pushstring(L, "package");
942  lua_rawget(L, -2);
943  lua_pushvalue(L, 1);
944  lua_rawget(L, -2);
945  if(!lua_isnil(L, -1) && !game_config::debug_lua) {
946  return 1;
947  }
948  lua_pop(L, 1);
949  lua_pushvalue(L, 1);
950  // stack is now [packagename] [wesnoth] [package] [packagename]
951 
952  if(lua_fileops::load_file(L) != 1) {
953  // should end with the file contents loaded on the stack. actually it will call lua_error otherwise, the return 0 is redundant.
954  // stack is now [packagename] [wesnoth] [package] [chunk]
955  return 0;
956  }
957  DBG_LUA << "require: loaded a file, now calling it\n";
958 
959  if (!this->protected_call(L, 0, 1, std::bind(&lua_kernel_base::log_error, this, _1, _2))) {
960  // historically if wesnoth.require fails it just yields nil and some logging messages, not a lua error
961  return 0;
962  }
963  // stack is now [packagename] [wesnoth] [package] [results]
964 
965  lua_pushvalue(L, 1);
966  lua_pushvalue(L, -2);
967  // stack is now [packagename] [wesnoth] [package] [results] [packagename] [results]
968  // Add the return value to the table.
969 
970  lua_settable(L, -4);
971  // stack is now [packagename] [wesnoth] [package] [results]
972  return 1;
973 }
975 {
976  lua_push(L, my_name());
977  return 1;
978 }
980 {
981  char const *m = luaL_checkstring(L, 2);
994  return 0;
995 }
997 {
998  std::string err_msg = "unknown modifiable property of game_config: ";
999  err_msg += luaL_checkstring(L, 2);
1000  return luaL_argerror(L, 2, err_msg.c_str());
1001 }
1002 /**
1003  * Loads the "package" package into the Lua environment.
1004  * This action is inherently unsafe, as Lua scripts will now be able to
1005  * load C libraries on their own, hence granting them the same privileges
1006  * as the Wesnoth binary itself.
1007  */
1009 {
1010  lua_State *L = mState;
1012  lua_pushstring(L, "package");
1013  lua_call(L, 1, 0);
1014 }
1015 
1017 {
1018  lua_State* L = mState;
1019  lua_settop(L, 0);
1020  cmd_log_ << "Loading core...\n";
1021  luaW_getglobal(L, "wesnoth", "require");
1022  lua_pushstring(L, "lua/core.lua");
1023  if(!protected_call(1, 1)) {
1024  cmd_log_ << "Error: Failed to load core.\n";
1025  }
1026  lua_settop(L, 0);
1027 }
1028 
1029 /**
1030  * Gets all the global variable names in the Lua environment. This is useful for tab completion.
1031  */
1032 std::vector<std::string> lua_kernel_base::get_global_var_names()
1033 {
1034  std::vector<std::string> ret;
1035 
1036  lua_State *L = mState;
1037 
1038  int idx = lua_gettop(L);
1039  lua_getglobal(L, "_G");
1040  lua_pushnil(L);
1041 
1042  while (lua_next(L, idx+1) != 0) {
1043  if (lua_isstring(L, -2)) {
1044  ret.push_back(lua_tostring(L,-2));
1045  }
1046  lua_pop(L,1);
1047  }
1048  lua_settop(L, idx);
1049  return ret;
1050 }
1051 
1052 /**
1053  * Gets all attribute names of an extended variable name. This is useful for tab completion.
1054  */
1055 std::vector<std::string> lua_kernel_base::get_attribute_names(const std::string & input)
1056 {
1057  std::vector<std::string> ret;
1058  std::string base_path = input;
1059  std::size_t last_dot = base_path.find_last_of('.');
1060  std::string partial_name = base_path.substr(last_dot + 1);
1061  base_path.erase(last_dot);
1062  std::string load = "return " + base_path;
1063 
1064  lua_State* L = mState;
1065  int save_stack = lua_gettop(L);
1066  int result = luaL_loadstring(L, load.c_str());
1067  if(result != LUA_OK) {
1068  // 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.
1069  LOG_LUA << "Error when attempting tab completion:\n";
1070  LOG_LUA << luaL_checkstring(L, -1) << '\n';
1071  // Just return an empty list; no matches were found
1072  lua_settop(L, save_stack);
1073  return ret;
1074  }
1075 
1076  luaW_pcall(L, 0, 1);
1077  if(lua_istable(L, -1) || lua_isuserdata(L, -1)) {
1078  int top = lua_gettop(L);
1079  int obj = lua_absindex(L, -1);
1080  if(luaL_getmetafield(L, obj, "__tab_enum") == LUA_TFUNCTION) {
1081  lua_pushvalue(L, obj);
1082  lua_pushlstring(L, partial_name.c_str(), partial_name.size());
1083  luaW_pcall(L, 2, 1);
1084  ret = lua_check<std::vector<std::string>>(L, -1);
1085  } else if(lua_type(L, -1) != LUA_TTABLE) {
1086  LOG_LUA << "Userdata missing __tab_enum meta-function for tab completion";
1087  lua_settop(L, save_stack);
1088  return ret;
1089  } else {
1090  lua_settop(L, top);
1091  // Metafunction not found, so use lua_next to enumerate the table
1092  for(lua_pushnil(L); lua_next(L, obj); lua_pop(L, 1)) {
1093  if(lua_type(L, -2) == LUA_TSTRING) {
1094  std::string attr = lua_tostring(L, -2);
1095  if(attr.empty()) {
1096  continue;
1097  }
1098  if(!isalpha(attr[0]) && attr[0] != '_') {
1099  continue;
1100  }
1101  if(std::any_of(attr.begin(), attr.end(), [](char c){
1102  return !isalpha(c) && !isdigit(c) && c != '_';
1103  })) {
1104  continue;
1105  }
1106  if(attr.substr(0, partial_name.size()) == partial_name) {
1107  ret.push_back(base_path + "." + attr);
1108  }
1109  }
1110  }
1111  }
1112  }
1113  lua_settop(L, save_stack);
1114  return ret;
1115 }
1116 
1118 {
1119  #ifdef __GNUC__
1120  #pragma GCC diagnostic push
1121  #pragma GCC diagnostic ignored "-Wold-style-cast"
1122  #endif
1123  return *reinterpret_cast<lua_kernel_base**>(lua_getextraspace(L));
1124  #ifdef __GNUC__
1125  #pragma GCC diagnostic pop
1126  #endif
1127 }
1128 
1130 {
1131  return seed_rng::next_seed();
1132 }
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:855
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:1022
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:920
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:1231
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:940
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 ...
static int intf_clone_wml(lua_State *L)
Returns a clone (deep copy) of the passed config, which can be either a normal config or a vconfig If...
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:377
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.
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.
#define LUA_TUSERDATA
Definition: lua.h:71
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:234
int intf_get_direction(lua_State *L)
Expose map_location::get_direction function to lua Arg 1: a location Arg 2: a direction Arg 3: (optio...
LUALIB_API int luaL_getmetafield(lua_State *L, int obj, const char *event)
Definition: lauxlib.cpp:772
LUA_API int lua_gettop(lua_State *L)
Definition: lapi.cpp:167
LUA_API int lua_gettable(lua_State *L, int idx)
Definition: lapi.cpp:612
LUAMOD_API int luaopen_math(lua_State *L)
Definition: lmathlib.cpp:398
LUA_API int lua_getglobal(lua_State *L, const char *name)
Definition: lapi.cpp:605
const attribute_value * get(config_key_type key) const
Returns a pointer to the attribute with the given key or nullptr if it does not exist.
Definition: config.cpp:744
LUA_API void lua_settable(lua_State *L, int idx)
Definition: lapi.cpp:766
#define return_string_attrib(name, accessor)
Definition: lua_common.hpp:217
int intf_textdomain(lua_State *L)
Creates an interface for gettext.
Definition: lua_common.cpp: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:109
#define lua_tonumber(L, i)
Definition: lua.h:341
#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:265
int intf_remove_dialog_item(lua_State *L)
Removes an entry from a list.
Definition: lua_gui2.cpp:691
void lua_push(lua_State *L, const T &val)
Definition: push_check.hpp:371
static int intf_wml_tostring(lua_State *L)
Dumps a wml table or userdata wml object into a pretty string.
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:800
#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:965
std::vector< std::string > split(const std::string &val, const char c, const int flags)
Splits a (comma-)separated string into a vector of pieces.
int intf_vector_diff(lua_State *L)
Expose map_location::vector_difference to lua.
LUAMOD_API int luaopen_base(lua_State *L)
Definition: lbaselib.cpp:486
int rest_heal_amount
Definition: game_config.cpp:61
LUA_API void * lua_newuserdata(lua_State *L, size_t size)
Definition: lapi.cpp:1184
int intf_distance_between(lua_State *L)
Expose map_location distance_between.
void remove_single_widget_definition(const std::string &widget_type, const std::string &definition_id)
Removes a widget definition from the default GUI.
#define lua_pop(L, n)
Definition: lua.h:344
int intf_set_dialog_focus(lua_State *L)
Sets a widget to have the focus.
Definition: lua_gui2.cpp:843
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.
One of the realizations of serialization/validator.hpp abstract validator.
static const char * name(const std::vector< SDL_Joystick *> &joysticks, const std::size_t index)
Definition: joystick.cpp:48
int intf_get_relative_dir(lua_State *L)
Expose map_location get_relative_dir.
#define LUA_TSTRING
Definition: lua.h:68
void write(std::ostream &out, const configr_of &cfg, unsigned int level)
Definition: parser.cpp:752
LUAMOD_API int luaopen_coroutine(lua_State *L)
Definition: lcorolib.cpp:164
LUALIB_API int luaL_argerror(lua_State *L, int arg, const char *extramsg)
Definition: lauxlib.cpp:164
LUAMOD_API int luaopen_os(lua_State *L)
Definition: loslib.cpp:405
std::string deprecated_message(const std::string &elem_name, DEP_LEVEL level, const version_info &version, const std::string &detail)
Definition: deprecation.cpp:29
#define return_int_attrib(name, accessor)
Definition: lua_common.hpp:226
void load_core()
Loads the "core" library into the Lua environment.
bool luaW_getglobal(lua_State *L, const std::vector< std::string > &path)
Pushes the value found by following the variadic names (char *), if the value is not nil...
Definition: lua_common.cpp: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
bool luaW_toboolean(lua_State *L, int n)
Definition: lua_common.cpp:870
void read(config &cfg, std::istream &in, abstract_validator *validator)
Definition: parser.cpp:615
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)
int intf_set_dialog_tooltip(lua_State *L)
Sets the value of a widget on the current dialog.
Definition: lua_gui2.cpp:582
#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
std::unique_ptr< std::istream > scoped_istream
Definition: filesystem.hpp:39
int kill_experience
Definition: game_config.cpp:57
static int intf_parse_wml(lua_State *L)
Parses a WML string into a config; does not preprocess or validate.
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:390
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:819
int luaW_pcall_internal(lua_State *L, int nArgs, int nRets)
Definition: lua_common.cpp:994
#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.
LUA_API void lua_len(lua_State *L, int idx)
Definition: lapi.cpp:1156
LUAMOD_API int() luaopen_utf8(lua_State *L)
Definition: lutf8lib.cpp:250
virtual int impl_game_config_get(lua_State *L)
#define LUA_ERRGCMM
Definition: lua.h:52
int show_popup_dialog(lua_State *L)
Displays a popup message.
Definition: lua_gui2.cpp:363
int intf_vector_negation(lua_State *L)
Expose map_location::vector_negation to lua.
LUALIB_API int luaL_newmetatable(lua_State *L, const char *tname)
Definition: lauxlib.cpp:299
LUA_API void * lua_touserdata(lua_State *L, int idx)
Definition: lapi.cpp:413
#define LUA_ERRERR
Definition: lua.h:53
void run(char const *prog, const std::string &name, int nArgs=0)
Runs a plain script.
static int intf_random(lua_State *L)
Returns a random numer, same interface as math.random.
#define lua_isnil(L, n)
Definition: lua.h:355
int intf_print(lua_State *L)
Replacement print function – instead of printing to std::cout, print to the command log...
std::size_t i
Definition: function.cpp:933
int intf_set_dialog_value(lua_State *L)
Sets the value of a widget on the current dialog.
Definition: lua_gui2.cpp:453
logger & err()
Definition: log.cpp:78
LUALIB_API lua_Integer luaL_checkinteger(lua_State *L, int arg)
Definition: lauxlib.cpp:430
std::string get_wml_location(const std::string &filename, const std::string &current_dir)
Returns a complete path to the actual WML file or directory or an empty string if the file isn&#39;t pres...
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_load_wml(lua_State *L)
Loads a WML file into a config.
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
int combat_experience
Definition: game_config.cpp:58
LUA_API void lua_pushvalue(lua_State *L, int idx)
Definition: lapi.cpp:237
const bool & debug
#define debug(x)
#define LUA_ERRMEM
Definition: lua.h:51
int intf_get_adjacent_tiles(lua_State *L)
Expose map_location get_adjacent_tiles.
int load_file(lua_State *L)
Loads a Lua file and pushes the contents on the stack.
LUA_API int lua_isnumber(lua_State *L, int idx)
Definition: lapi.cpp:276
virtual void log_error(char const *msg, char const *context="Lua error")
Error reporting mechanisms, used by virtual methods protected_call and load_string.
const version_info wesnoth_version(VERSION)
rng * generator
This generator is automatically synced during synced context.
Definition: random.cpp:60
bool load_string(char const *prog, const std::string &name, error_handler)
#define lua_call(L, n, r)
Definition: lua.h:274
int intf_set_dialog_callback(lua_State *L)
Sets a callback on a widget of the current dialog.
Definition: lua_gui2.cpp:749
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:242
static int impl_name_generator_call(lua_State *L)
uint32_t next_seed()
Definition: seed_rng.cpp:45
LUA_API int lua_error(lua_State *L)
Definition: lapi.cpp:1114
logger & warn()
Definition: log.cpp:84
std::vector< std::string > get_attribute_names(const std::string &var_path)
Gets all attribute names of an extended variable name.
#define LUA_OK
Definition: lua.h:47
#define lua_istable(L, n)
Definition: lua.h:353
DEP_LEVEL
See https://wiki.wesnoth.org/CompatibilityStandards for more info.
Definition: deprecation.hpp:19
virtual void throw_exception(char const *msg, char const *context="Lua error")
static int intf_wml_matches_filter(lua_State *L)
#define lua_insert(L, idx)
Definition: lua.h:369
void luaW_pushvconfig(lua_State *L, const vconfig &cfg)
Pushes a vconfig on the top of the stack.
Definition: lua_common.cpp:509
A variable-expanding proxy for the config class.
Definition: variable.hpp:42
const config & get_config() const
Definition: variable.hpp:75
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
LUA_API int lua_geti(lua_State *L, int idx, lua_Integer n)
Definition: lapi.cpp:628
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.
std::map< std::string, struct preproc_define > preproc_map
#define e
Realization of serialization/validator.hpp abstract validator.
int intf_get_dialog_value(lua_State *L)
Gets the value of a widget on the current dialog.
Definition: lua_gui2.cpp:600
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:988
int show_message_box(lua_State *L)
Displays a simple message box.
Definition: lua_gui2.cpp:416
A config object defines a single node in a WML file, with access to child nodes.
Definition: config.hpp:92
filesystem::scoped_istream preprocess_file(const std::string &fname, preproc_map *defines)
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
static map_location::DIRECTION n
LUA_API void lua_pushinteger(lua_State *L, lua_Integer n)
Definition: lapi.cpp:466
void throwing_run(char const *prog, const std::string &name, int nArgs)
Runs a plain script, but reports errors by throwing lua_error.
#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:780
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
#define LUA_TBOOLEAN
Definition: lua.h:65
int intf_set_dialog_visible(lua_State *L)
Sets the visiblity of a widget in the current dialog.
Definition: lua_gui2.cpp:873
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