The Battle for Wesnoth 1.21.0-dev
 
Loading...
Searching...
No Matches
lua_kernel_base.cpp
Go to the documentation of this file.
1/*
2 Copyright (C) 2014 - 2025
3 by Chris Beck <render787@gmail.com>
4 Part of the Battle for Wesnoth Project https://www.wesnoth.org/
5
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY.
12
13 See the COPYING file for more details.
14*/
15
17
18#include "game_config.hpp"
19#include "game_errors.hpp"
20#include "gui/core/gui_definition.hpp" // for remove_single_widget_definition
21#include "log.hpp"
22#include "lua_jailbreak_exception.hpp" // for lua_jailbreak_exception
23#include "seed_rng.hpp"
25#include "deprecation.hpp"
26#include "language.hpp" // for get_language
27#include "team.hpp" // for shroud_map
28
29#ifdef DEBUG_LUA
31#endif
32
40#include "scripting/lua_wml.hpp"
44#include "scripting/lua_rng.hpp"
47
48#include "game_version.hpp" // for do_version_check, etc
49
50#include <functional>
54#include "utils/scope_exit.hpp"
55
56#include <SDL3/SDL_timer.h>
57
58#include <cstring>
59#include <string>
60#include <sstream>
61#include <vector>
62#include <numeric>
63
64#include "lua/wrapper_lualib.h"
65
66static lg::log_domain log_scripting_lua("scripting/lua");
67static lg::log_domain log_user("scripting/lua/user");
68#define DBG_LUA LOG_STREAM(debug, log_scripting_lua)
69#define LOG_LUA LOG_STREAM(info, log_scripting_lua)
70#define WRN_LUA LOG_STREAM(warn, log_scripting_lua)
71#define ERR_LUA LOG_STREAM(err, log_scripting_lua)
72
73// Registry key for metatable
74static const char * Gen = "name generator";
75static const char * Version = "version";
76// Registry key for lua interpreter environment
77static const char * Interp = "lua interpreter";
78
79// Callback implementations
80
81/**
82 * Compares two versions.
83 * - Args 1,2: version strings
84 * - Ret 1: comparison result
85 */
86template<VERSION_COMP_OP vop>
87static int impl_version_compare(lua_State* L)
88{
89 version_info& v1 = *static_cast<version_info*>(luaL_checkudata(L, 1, Version));
90 version_info& v2 = *static_cast<version_info*>(luaL_checkudata(L, 2, Version));
91 const bool result = do_version_check(v1, vop, v2);
92 lua_pushboolean(L, result);
93 return 1;
94}
95
96/**
97 * Decomposes a version into its component parts
98 */
99static int impl_version_get(lua_State* L)
100{
101 version_info& vers = *static_cast<version_info*>(luaL_checkudata(L, 1, Version));
102 if(lua_isinteger(L, 2)) {
103 int n = lua_tointeger(L, 2) - 1;
104 auto& components = vers.components();
105 if(n >= 0 && std::size_t(n) < components.size()) {
106 lua_pushinteger(L, vers.components()[n]);
107 } else {
108 lua_pushnil(L);
109 }
110 return 1;
111 }
112 char const *m = luaL_checkstring(L, 2);
113 return_int_attrib("major", vers.major_version());
114 return_int_attrib("minor", vers.minor_version());
115 return_int_attrib("revision", vers.revision_level());
116 return_bool_attrib("is_canonical", vers.is_canonical());
117 return_string_attrib("special", vers.special_version());
118 if(char sep = vers.special_version_separator()) {
119 return_string_attrib("sep", std::string(1, sep));
120 } else if(strcmp(m, "sep") == 0) {
121 lua_pushnil(L);
122 return 1;
123 }
124 return 0;
125}
126
127static int impl_version_dir(lua_State* L)
128{
129 static const std::vector<std::string> fields{"major", "minor", "revision", "is_canonical", "special", "sep"};
130 lua_push(L, fields);
131 return 1;
132}
133
134/**
135 * Destroy a version
136 */
137static int impl_version_finalize(lua_State* L)
138{
139 version_info* vers = static_cast<version_info*>(luaL_checkudata(L, 1, Version));
140 vers->~version_info();
141 return 0;
142}
143
144/**
145 * Convert a version to string form
146 */
147static int impl_version_tostring(lua_State* L)
148{
149 version_info& vers = *static_cast<version_info*>(luaL_checkudata(L, 1, Version));
150 lua_push(L, vers.str());
151 return 1;
152}
153
154/**
155 * Builds a version from its component parts, or parses it from a string
156 */
157static int intf_make_version(lua_State* L)
158{
159 // If passed a version, just return it unchanged
160 if(luaL_testudata(L, 1, Version)) {
161 lua_settop(L, 1);
162 return 1;
163 }
164 // If it's a string, parse it; otherwise build from components
165 // The components method only supports canonical versions
166 if(lua_type(L, 1) == LUA_TSTRING) {
167 new(L) version_info(lua_check<std::string>(L, 1));
168 } else {
169 int major = luaL_checkinteger(L, 1), minor = luaL_optinteger(L, 2, 0), rev = luaL_optinteger(L, 3, 0);
170 std::string sep, special;
171 if(lua_type(L, -1) == LUA_TSTRING) {
172 special = lua_tostring(L, -1);
173 if(!special.empty() && utils::portable_isalpha(special[0])) {
174 sep.push_back('+');
175 } else {
176 sep.push_back(special[0]);
177 special = special.substr(1);
178 }
179 } else {
180 sep.push_back(0);
181 }
182 new(L) version_info(major, minor, rev, sep[0], special);
183 }
184 if(luaL_newmetatable(L, Version)) {
185 static const luaL_Reg metafuncs[] {
186 { "__index", &impl_version_get },
187 { "__dir", &impl_version_dir },
188 { "__tostring", &impl_version_tostring },
189 { "__lt", &impl_version_compare<VERSION_COMP_OP::OP_LESS> },
190 { "__le", &impl_version_compare<VERSION_COMP_OP::OP_LESS_OR_EQUAL> },
191 { "__eq", &impl_version_compare<VERSION_COMP_OP::OP_EQUAL> },
192 { "__gc", &impl_version_finalize },
193 { nullptr, nullptr }
194 };
195 luaL_setfuncs(L, metafuncs, 0);
196 luaW_table_set<std::string>(L, -1, "__metatable", Version);
197 }
198 lua_setmetatable(L, -2);
199 return 1;
200}
201
202/**
203 * Returns the current Wesnoth version
204 */
205static int intf_current_version(lua_State* L) {
206 lua_settop(L, 0);
209 return 1;
210}
211
212static int intf_safe_tostring(lua_State* L)
213{
214 // tostring requires one argument. Report an error when the stack has no first value.
215 luaL_checkany(L, 1);
216
217 // Shared __tostring methods make Lua's standard conversion safe for functions,
218 // threads, and light userdata. Tables and full userdata use individual metatables,
219 // so values without __tostring are handled below instead of passed to luaL_tolstring.
220
221 // If the value defines __tostring, use it exactly as Lua normally would.
222 // The generic type name below is only for values without their own string representation.
223 const int tostring_type = luaL_getmetafield(L, 1, "__tostring");
224 if(tostring_type != LUA_TNIL
225 || (lua_type(L, 1) != LUA_TTABLE && lua_type(L, 1) != LUA_TUSERDATA)) {
226 if(tostring_type != LUA_TNIL) {
227 lua_pop(L, 1);
228 }
229 luaL_tolstring(L, 1, nullptr);
230 return 1;
231 }
232
233 // Named metatables already provide base descriptions. Reuse them for stringification.
234 const int name_type = luaL_getmetafield(L, 1, "__name");
235 if(name_type == LUA_TSTRING) {
236 return 1;
237 }
238 if(name_type != LUA_TNIL) {
239 lua_pop(L, 1);
240 }
241 lua_pushstring(L, luaL_typename(L, 1));
242 return 1;
243}
244
245static int intf_std_print(lua_State* L)
246{
247 // Lua's print calls luaL_tolstring directly instead of the global
248 // tostring function. Tables and userdata without __tostring would therefore
249 // include memory addresses. Use Wesnoth's replacement without changing the
250 // order in which arguments are converted and written.
251 const int nargs = lua_gettop(L);
252 lua_getglobal(L, "tostring");
253 for(int i = 1; i <= nargs; ++i) {
254 lua_pushvalue(L, -1);
255 lua_pushvalue(L, i);
256 const int status = lua_pcall(L, 1, 1, 0);
257 // A jailbreak exception must not be returned as a normal Lua error.
259 if(status != LUA_OK) {
260 return lua_error(L);
261 }
262
263 std::size_t length = 0;
264 const char* string = luaL_checklstring(L, -1, &length);
265 if(i > 1) {
266 lua_writestring("\t", 1);
267 }
268 lua_writestring(string, length);
269 lua_pop(L, 1);
270 }
271 lua_pop(L, 1);
272 lua_writeline();
273 return 0;
274}
275
276/**
277 * Replacement print function -- instead of printing to std::cout, print to the command log.
278 * Intended to be bound to this' command_log at registration time.
279 */
281{
282 DBG_LUA << "intf_print called:";
283 std::size_t nargs = lua_gettop(L);
284
285 lua_getglobal(L, "tostring");
286 for (std::size_t i = 1; i <= nargs; ++i) {
287 lua_pushvalue(L, -1); // function to call: "tostring"
288 lua_pushvalue(L, i); // value to pass through tostring() before printing
289 lua_call(L, 1, 1);
290 const char * str = lua_tostring(L, -1);
291 if (!str) {
292 LOG_LUA << "'tostring' must return a value to 'print'";
293 str = "";
294 }
295 if (i > 1) {
296 cmd_log_ << "\t"; //separate multiple args with tab character
297 }
298 cmd_log_ << str;
299 DBG_LUA << "'" << str << "'";
300 lua_pop(L, 1); // Pop the output of tostrring()
301 }
302 lua_pop(L, 1); // Pop 'tostring' global
303
304 cmd_log_ << "\n";
305 DBG_LUA;
306
307 return 0;
308}
309
310static void impl_warn(void* p, const char* msg, int tocont) {
311 static const char*const prefix = "Warning:\n ";
312 static std::ostringstream warning(prefix);
313 warning.seekp(0, std::ios::end);
314 warning << msg << ' ';
315 if(!tocont) {
316 auto L = reinterpret_cast<lua_State*>(p);
317 luaW_getglobal(L, "debug", "traceback");
318 lua_push(L, warning.str());
319 lua_pushinteger(L, 2);
320 lua_call(L, 2, 1);
321 auto& lk = lua_kernel_base::get_lua_kernel<lua_kernel_base>(L);
322 lk.add_log_to_console(luaL_checkstring(L, -1));
323 warning.str(prefix);
324 }
325}
326
327void lua_kernel_base::add_log_to_console(const std::string& msg) {
328 cmd_log_ << msg << "\n";
329 DBG_LUA << "'" << msg << "'";
330}
331
332/**
333 * Replacement load function. Mostly the same as regular load, but disallows loading binary chunks
334 * due to CVE-2018-1999023.
335 */
336static int intf_load(lua_State* L)
337{
338 std::string chunk = luaL_checkstring(L, 1);
339 const char* name = luaL_optstring(L, 2, chunk.c_str());
340 std::string mode = luaL_optstring(L, 3, "t");
341 bool override_env = !lua_isnone(L, 4);
342
343 if(mode != "t") {
344 return luaL_argerror(L, 3, "binary chunks are not allowed for security reasons");
345 }
346
347 int result = luaL_loadbufferx(L, chunk.data(), chunk.length(), name, "t");
348 if(result != LUA_OK) {
349 lua_pushnil(L);
350 // Move the nil as the first return value, like Lua's own load() does.
351 lua_insert(L, -2);
352
353 return 2;
354 }
355
356 if(override_env) {
357 // Copy "env" to the top of the stack.
358 lua_pushvalue(L, 4);
359 // Set "env" as the first upvalue.
360 const char* upvalue_name = lua_setupvalue(L, -2, 1);
361 if(upvalue_name == nullptr) {
362 // lua_setupvalue() didn't remove the copy of "env" from the stack, so we need to do it ourselves.
363 lua_pop(L, 1);
364 }
365 }
366
367 return 1;
368}
369
370/**
371 * Wrapper for pcall and xpcall functions to rethrow jailbreak exceptions
372 */
373static int intf_pcall(lua_State *L)
374{
375 lua_CFunction function = lua_tocfunction(L, lua_upvalueindex(1));
376 assert(function); // The upvalue should be Lua's pcall or xpcall, or else something is very wrong.
377
378 int nRets = function(L);
379
380 // If a jailbreak exception was stored while running (x)pcall, rethrow it so Lua doesn't continue.
382
383 return nRets;
384}
385
386// The show lua console callback is similarly a method of lua kernel
388{
390 std::string message = "There is already an external logger attached to this lua kernel, you cannot open the lua console right now.";
391 log_error(message.c_str());
392 cmd_log_ << message << "\n";
393 return 0;
394 }
395
396 return lua_gui2::show_lua_console(L, this);
397}
398
399static int impl_name_generator_call(lua_State *L)
400{
401 name_generator* gen = static_cast<name_generator*>(luaL_checkudata(L, 1, Gen));
402 lua_pushstring(L, gen->generate().c_str());
403 return 1;
404}
405
406static int impl_name_generator_tostring(lua_State *L)
407{
408 name_generator* gen = static_cast<name_generator*>(luaL_checkudata(L, 1, Gen));
409 luaW_getglobal(L, "string", "format");
410 lua_pushstring(L, "%s: %s");
411 lua_pushstring(L, Gen);
412 lua_pushstring(L, gen->type().c_str());
413 lua_call(L, 2, 1);
414 return 1;
415}
416
417static int impl_name_generator_collect(lua_State *L)
418{
419 name_generator* gen = static_cast<name_generator*>(luaL_checkudata(L, 1, Gen));
420 gen->~name_generator();
421 return 0;
422}
423
424static int intf_name_generator(lua_State *L)
425{
426 std::string type = luaL_checkstring(L, 1);
427 name_generator* gen = nullptr;
428 try {
429 if(type == "markov" || type == "markov_chain") {
430 std::vector<std::string> input;
431 if(lua_istable(L, 2)) {
432 input = lua_check<std::vector<std::string>>(L, 2);
433 } else {
434 input = utils::parenthetical_split(luaW_checktstring(L, 2).str(), ',');
435 }
436 int chain_sz = luaL_optinteger(L, 3, 2);
437 int max_len = luaL_optinteger(L, 4, 12);
438 gen = new(L) markov_generator(input, chain_sz, max_len);
439 // Ensure the pointer didn't change when cast
440 assert(static_cast<void*>(gen) == dynamic_cast<markov_generator*>(gen));
441 } else if(type == "context_free" || type == "cfg" || type == "CFG") {
442 if(lua_istable(L, 2)) {
443 std::map<std::string, std::vector<std::string>> data;
444 for(lua_pushnil(L); lua_next(L, 2); lua_pop(L, 1)) {
445 if(lua_type(L, -2) != LUA_TSTRING) {
446 lua_pushstring(L, "CFG generator: invalid nonterminal name (must be a string)");
447 return lua_error(L);
448 }
449 if(lua_isstring(L, -1)) {
450 auto& productions = data[lua_tostring(L,-2)] = utils::split(luaW_checktstring(L,-1).str(), '|');
451 if(productions.size() > 1) {
452 deprecated_message("wesnoth.name_generator('cfg', {nonterminal = 'a|b'})", DEP_LEVEL::INDEFINITE, "1.17", "Non-terminals should now be assigned an array of productions instead of a single string containing productions separated by | - but a single string is fine if it's only one production");
453 }
454 } else if(lua_istable(L, -1)) {
455 const auto& split = lua_check<std::vector<t_string>>(L, -1);
456 auto& productions = data[lua_tostring(L,-2)];
457 std::transform(split.begin(), split.end(), std::back_inserter(productions), std::mem_fn(&t_string::str));
458 } else {
459 lua_pushstring(L, "CFG generator: invalid nonterminal value (must be a string or list of strings)");
460 return lua_error(L);
461 }
462 }
463 if(!data.empty()) {
465 }
466 } else {
468 }
469 if(gen) {
470 assert(static_cast<void*>(gen) == dynamic_cast<context_free_grammar_generator*>(gen));
471 }
472 } else {
473 return luaL_argerror(L, 1, "should be either 'markov_chain' or 'context_free'");
474 }
475 }
476 catch (const name_generator_invalid_exception& ex) {
477 lua_pushstring(L, ex.what());
478 return lua_error(L);
479 }
480
481 // We set the metatable now, even if the generator is invalid, so that it
482 // will be properly collected if it was invalid.
483 luaL_getmetatable(L, Gen);
484 lua_setmetatable(L, -2);
485
486 return 1;
487}
488
489/**
490* Logs a message
491* Arg 1: (optional) Logger
492* Arg 2: Message
493*/
494static int intf_log(lua_State *L) {
495 const std::string& logger = lua_isstring(L, 2) ? luaL_checkstring(L, 1) : "";
496 std::string msg = lua_isstring(L, 2) ? luaL_checkstring(L, 2) : luaL_checkstring(L, 1);
497 if(msg.empty() || msg.back() != '\n') {
498 msg += '\n';
499 }
500
501 if(logger == "err" || logger == "error") {
502 LOG_STREAM(err, log_user) << msg;
503 } else if(logger == "warn" || logger == "wrn" || logger == "warning") {
504 LOG_STREAM(warn, log_user) << msg;
505 } else if((logger == "debug" || logger == "dbg")) {
506 LOG_STREAM(debug, log_user) << msg;
507 } else {
508 LOG_STREAM(info, log_user) << msg;
509 }
510 return 0;
511}
512
513/**
514 * Logs a deprecation message. See deprecation.cpp for details
515 * Arg 1: Element to be deprecated.
516 * Arg 2: Deprecation level.
517 * Arg 3: Version when element may be removed.
518 * Arg 4: Additional detail message.
519 */
520static int intf_deprecated_message(lua_State* L) {
521 const std::string elem = luaL_checkstring(L, 1);
522 // This could produce an invalid deprecation level, but that possibility is handled in deprecated_message()
523 const DEP_LEVEL level = DEP_LEVEL(luaL_checkinteger(L, 2));
524 const std::string ver_str = lua_isnoneornil(L, 3) ? "" : luaL_checkstring(L, 3);
525 const std::string detail = luaW_checktstring(L, 4);
526 const version_info ver = ver_str.empty() ? game_config::wesnoth_version.str() : ver_str;
527 const std::string msg = deprecated_message(elem, level, ver, detail);
528 if(level < DEP_LEVEL::INDEFINITE || level >= DEP_LEVEL::REMOVED) {
529 // Invalid deprecation level or level 4 deprecation should raise an interpreter error
530 lua_push(L, msg);
531 return lua_error(L);
532 }
533 lua_warning(L, msg.c_str(), false);
534 return 0;
535}
536
537/**
538 * Converts a Lua array to a named tuple.
539 * Arg 1: A Lua array
540 * Arg 2: An array of strings
541 * Ret: A copy of arg 1 that's now a named tuple with the names in arg 2.
542 * The copy will only include the array portion of the input array.
543 * Any non-integer keys or non-consecutive keys will be gone.
544 * Note: This exists so that wml.tag can use it but is not really intended as a public API.
545 */
546static int intf_named_tuple(lua_State* L)
547{
548 if(!lua_istable(L, 1)) {
549 return luaW_type_error(L, 1, lua_typename(L, LUA_TTABLE));
550 }
551 auto names = lua_check<std::vector<std::string>>(L, 2);
552 lua_len(L, 1);
553 int len = luaL_checkinteger(L, -1);
555 for(int i = 1; i <= std::max<int>(len, names.size()); i++) {
556 lua_geti(L, 1, i);
557 lua_seti(L, -2, i);
558 }
559 return 1;
560}
561
562static int intf_parse_shroud_bitmap(lua_State* L)
563{
564 shroud_map temp;
565 temp.set_enabled(true);
566 temp.read(luaL_checkstring(L, 1));
567 std::set<map_location> locs;
568 for(int x = 1; x <= temp.width(); x++) {
569 for(int y = 1; y <= temp.height(); y++) {
570 if(!temp.value(x, y)) {
571 locs.emplace(x, y, wml_loc());
572 }
573 }
574 }
575 luaW_push_locationset(L, locs);
576 return 1;
577}
578
579static int intf_make_shroud_bitmap(lua_State* L)
580{
581 shroud_map temp;
582 temp.set_enabled(true);
583 auto locs = luaW_check_locationset(L, 1);
584 for(const auto& loc : locs) {
585 temp.clear(loc.wml_x(), loc.wml_y());
586 }
587 lua_push(L, temp.write());
588 return 1;
589}
590
591/**
592* Returns the time stamp, exactly as [set_variable] time=stamp does.
593* - Ret 1: integer
594*/
595static int intf_ms_since_init(lua_State *L) {
596 lua_pushinteger(L, SDL_GetTicks());
597 return 1;
598}
599
600static int intf_get_language(lua_State* L)
601{
602 lua_push(L, get_language().localename);
603 return 1;
604}
605
606static void dir_meta_helper(lua_State* L, std::vector<std::string>& keys)
607{
608 switch(luaL_getmetafield(L, -1, "__dir")) {
609 case LUA_TFUNCTION:
610 lua_pushvalue(L, 1);
611 lua_push(L, keys);
612 if(lua_pcall(L, 2, 1, 0) == LUA_OK) {
613 keys = lua_check<std::vector<std::string>>(L, -1);
614 } else {
615 lua_warning(L, "wesnoth.print_attributes: __dir metamethod raised an error", false);
616 }
617 break;
618 case LUA_TTABLE:
619 auto dir_keys = lua_check<std::vector<std::string>>(L, -1);
620 std::copy(dir_keys.begin(), dir_keys.end(), std::back_inserter(keys));
621 break;
622 }
623 lua_pop(L, 1);
624}
625
626// This is a separate function so I can use a protected call on it to catch errors.
627static int impl_is_deprecated(lua_State* L)
628{
629 auto key = luaL_checkstring(L, 2);
630 auto type = lua_getfield(L, 1, key);
631 if(type == LUA_TTABLE) {
632 lua_pushliteral(L, "__deprecated");
633 if(lua_rawget(L, -2) == LUA_TBOOLEAN) {
634 auto deprecated = luaW_toboolean(L, -1);
635 lua_pushboolean(L, deprecated);
636 return 1;
637 }
638 lua_pop(L, 1);
639 }
640 lua_pushboolean(L, false);
641 return 1;
642}
643
644// This is also a separate function so I can use a protected call on it to catch errors.
645static int impl_get_dir_suffix(lua_State*L)
646{
647 auto key = luaL_checkstring(L, 2);
648 std::string suffix = " ";
649 auto type = lua_getfield(L, 1, key);
650 if(type == LUA_TTABLE) {
651 suffix = "†";
652 } else if(type == LUA_TFUNCTION) {
653 suffix = "Æ’";
654 } else if(type == LUA_TUSERDATA) {
655 lua_getglobal(L, "getmetatable");
656 lua_pushvalue(L, -2);
657 lua_call(L, 1, 1);
658 if(lua_type(L, -1) == LUA_TSTRING) {
659 auto meta = lua_check<std::string>(L, -1);
660 if(meta == "function") {
661 suffix = "Æ’";
662 }
663 }
664 lua_pop(L, 1);
665 if(suffix.size() == 1) {
666 // ie, the above block didn't identify it as a function
667 if(auto t = luaL_getmetafield(L, -1, "__dir_tablelike"); t == LUA_TBOOLEAN) {
668 if(luaW_toboolean(L, -1)) {
669 suffix = "†";
670 }
671 lua_pop(L, 1);
672 } else if(t != LUA_TNIL) {
673 lua_pop(L, 1);
674 }
675 }
676 }
677 suffix = " " + suffix;
678 lua_pushlstring(L, suffix.c_str(), suffix.size());
679 return 1;
680}
681
682/**
683 * This function does the actual work of grabbing all the attribute names.
684 * It's a separate function so that it can be used by tab-completion as well.
685 */
686std::vector<std::string> luaW_get_attributes(lua_State* L, int idx)
687{
688 if(idx < 0 && idx >= -lua_gettop(L)) {
689 idx = lua_absindex(L, idx);
690 }
691 std::vector<std::string> keys;
692 if(lua_istable(L, idx)) {
693 // Walk the metatable chain (as long as __index is a table)...
694 // If we reach an __index that's a function, check for a __dir metafunction.
695 int save_top = lua_gettop(L);
696 lua_pushvalue(L, idx);
697 ON_SCOPE_EXIT(&) {
698 lua_settop(L, save_top);
699 };
700 do {
701 int table_idx = lua_absindex(L, -1);
702 for(lua_pushnil(L); lua_next(L, table_idx); lua_pop(L, 1)) {
703 if(lua_type(L, -2) == LUA_TSTRING) {
704 keys.push_back(lua_tostring(L,-2));
705 }
706 }
707 // Two possible exit cases:
708 // 1. getmetafield returns TNIL because there is no __index
709 // In this case, the stack is unchanged, so the while condition is still true.
710 // 2. The __index is not a table
711 // In this case, obviously the while condition fails
712 if(luaL_getmetafield(L, table_idx, "__index") == LUA_TNIL) break;
713 } while(lua_istable(L, -1));
714 if(lua_isfunction(L, -1)) {
715 lua_pop(L, 1);
716 dir_meta_helper(L, keys);
717 }
718 } else if(lua_isuserdata(L, idx) && !lua_islightuserdata(L, idx)) {
719 lua_pushvalue(L, idx);
720 dir_meta_helper(L, keys);
721 lua_pop(L, 1);
722 }
723 // Sort and remove any duplicates
724 std::sort(keys.begin(), keys.end());
725 auto new_end = std::unique(keys.begin(), keys.end());
726 new_end = std::remove_if(keys.begin(), new_end, [L, idx](const std::string& key) {
727 if(key.compare(0, 2, "__") == 0) {
728 return true;
729 }
730 int save_top = lua_gettop(L);
731 ON_SCOPE_EXIT(&) {
732 lua_settop(L, save_top);
733 };
734 // Exclude deprecated elements
735 // Some keys may be write-only, which would raise an exception here
736 // In that case we just ignore it and assume not deprecated
737 // (the __dir metamethod would be responsible for excluding deprecated write-only keys)
738 lua_pushcfunction(L, impl_is_deprecated);
739 lua_pushvalue(L, idx);
740 lua_push(L, key);
741 if(lua_pcall(L, 2, 1, 0) == LUA_OK) {
742 return luaW_toboolean(L, -1);
743 }
744 return false;
745 });
746 keys.erase(new_end, keys.end());
747 return keys;
748}
749
750/**
751 * Prints out a list of keys available in an object.
752 * A list of keys is gathered from the following sources:
753 * - For a table, all keys defined in the table
754 * - Any keys accessible through the metatable chain (if __index on the metatable is a table)
755 * - The output of the __dir metafunction
756 * - Filtering out any keys beginning with two underscores
757 * - Filtering out any keys for which object[key].__deprecated exists and is true
758 * The list is then sorted alphabetically and formatted into columns.
759 * - Arg 1: Any object
760 * - Arg 2: (optional) Function to use for output; defaults to _G.print
761 */
762static int intf_object_dir(lua_State* L)
763{
764 if(lua_isnil(L, 1)) return luaL_argerror(L, 1, "Can't dir() nil");
765 if(!lua_isfunction(L, 2)) {
766 luaW_getglobal(L, "print");
767 }
768 int fcn_idx = lua_gettop(L);
769 auto keys = luaW_get_attributes(L, 1);
770 std::size_t max_len = std::accumulate(keys.begin(), keys.end(), 0, [](std::size_t max, const std::string& next) {
771 return std::max(max, next.size());
772 });
773 // Let's limit to about 80 characters of total width with minimum 3 characters padding between columns
774 static const std::size_t MAX_WIDTH = 80, COL_PADDING = 3, SUFFIX_PADDING = 2;
775 std::size_t col_width = max_len + COL_PADDING + SUFFIX_PADDING;
776 std::size_t n_cols = (MAX_WIDTH + COL_PADDING) / col_width;
777 std::size_t n_rows = ceil(keys.size() / double(n_cols));
778 for(std::size_t i = 0; i < n_rows; i++) {
779 std::ostringstream line;
780 line.fill(' ');
781 line.setf(std::ios::left);
782 for(std::size_t j = 0; j < n_cols && j + (i * n_cols) < keys.size(); j++) {
783 int save_top = lua_gettop(L);
784 ON_SCOPE_EXIT(&) {
785 lua_settop(L, save_top);
786 };
787 lua_pushcfunction(L, impl_get_dir_suffix);
788 lua_pushvalue(L, 1);
789 const auto& key = keys[j + i * n_cols];
790 lua_pushlstring(L, key.c_str(), key.size());
791 std::string suffix = " !"; // Exclamation mark to indicate an error
792 if(lua_pcall(L, 2, 1, 0) == LUA_OK) {
793 suffix = luaL_checkstring(L, -1);
794 }
795 // This weird calculation is because width counts in bytes, not code points
796 // Since the suffix is a Unicode character, that messes up the alignment
797 line.width(col_width - SUFFIX_PADDING + suffix.size());
798 // Concatenate key and suffix beforehand so they share the same field width.
799 line << (key + suffix) << std::flush;
800 }
801 lua_pushvalue(L, fcn_idx);
802 lua_push(L, line.str());
803 lua_call(L, 1, 0);
804 }
805 return 0;
806}
807
808// End Callback implementations
809
810// Template which allows to push member functions to the lua kernel base into lua as C functions, using a shim
811typedef int (lua_kernel_base::*member_callback)(lua_State *L);
812
813template <member_callback method>
814int dispatch(lua_State *L) {
815 return ((lua_kernel_base::get_lua_kernel<lua_kernel_base>(L)).*method)(L);
816}
817
818// Ctor, initialization
820 : mState(luaL_newstate())
821 , cmd_log_()
822{
824 lua_State *L = mState;
825
826 cmd_log_ << "Initializing " << my_name() << "...\n";
827
828 // Define the CPP_function metatable ( so we can override print to point to a C++ member function, add certain functions for this kernel, etc. )
829 // Do it first of all in case C++ functions are ever used in the core Wesnoth libs loaded in the next step
830 cmd_log_ << "Adding boost function proxy...\n";
831
833
834 // Open safe libraries.
835 // Debug and OS are not, but most of their functions will be disabled below.
836 cmd_log_ << "Adding standard libs...\n";
837
838 static const luaL_Reg safe_libs[] {
839 { "", luaopen_base },
840 { "table", luaopen_table },
841 { "string", luaopen_string },
842 { "math", luaopen_math },
843 { "coroutine", luaopen_coroutine },
844 { "debug", luaopen_debug },
845 { "os", luaopen_os },
846 { "utf8", luaopen_utf8 }, // added in Lua 5.3
847 // Wesnoth libraries
848 { "stringx",lua_stringx::luaW_open },
849 { "mathx", lua_mathx::luaW_open },
850 { "wml", lua_wml::luaW_open },
851 { "gui", lua_gui2::luaW_open },
852 { "filesystem", lua_fileops::luaW_open },
853 { nullptr, nullptr }
854 };
855 for (luaL_Reg const *lib = safe_libs; lib->func; ++lib)
856 {
857 luaL_requiref(L, lib->name, lib->func, strlen(lib->name));
858 lua_pop(L, 1); /* remove lib */
859 }
860
861 // luaopen_base installs the standard tostring function, so install the replacement
862 // after library initialization and before any core or scenario Lua code can run.
863 lua_pushcfunction(L, intf_safe_tostring);
864 lua_setglobal(L, "tostring");
865
866 // Disable functions from os which we don't want.
867 lua_getglobal(L, "os");
868 lua_pushnil(L);
869 while(lua_next(L, -2) != 0) {
870 lua_pop(L, 1);
871 char const* function = lua_tostring(L, -1);
872 if(strcmp(function, "clock") == 0 || strcmp(function, "date") == 0
873 || strcmp(function, "time") == 0 || strcmp(function, "difftime") == 0) continue;
874 lua_pushnil(L);
875 lua_setfield(L, -3, function);
876 }
877 lua_pop(L, 1);
878
879 // Delete dofile and loadfile.
880 lua_pushnil(L);
881 lua_setglobal(L, "dofile");
882 lua_pushnil(L);
883 lua_setglobal(L, "loadfile");
884
885 // Store the error handler.
886 cmd_log_ << "Adding error handler...\n";
888
889
890 lua_settop(L, 0);
891
892 // Add some callback from the wesnoth lib
893 cmd_log_ << "Registering basic wesnoth API...\n";
894
895 static luaL_Reg const callbacks[] {
896 { "deprecated_message", &intf_deprecated_message },
897 { "textdomain", &lua_common::intf_textdomain },
898 { "dofile", &dispatch<&lua_kernel_base::intf_dofile> },
899 { "require", &dispatch<&lua_kernel_base::intf_require> },
900 { "kernel_type", &dispatch<&lua_kernel_base::intf_kernel_type> },
901 { "compile_formula", &lua_formula_bridge::intf_compile_formula},
902 { "eval_formula", &lua_formula_bridge::intf_eval_formula},
903 { "name_generator", &intf_name_generator },
904 { "named_tuple", &intf_named_tuple },
905 { "log", &intf_log },
906 { "ms_since_init", &intf_ms_since_init },
907 { "get_language", &intf_get_language },
908 { "version", &intf_make_version },
909 { "current_version", &intf_current_version },
910 { "print_attributes", &intf_object_dir },
911 { nullptr, nullptr }
912 };
913
914 lua_getglobal(L, "wesnoth");
915 if (!lua_istable(L,-1)) {
916 lua_newtable(L);
917 }
918 luaL_setfuncs(L, callbacks, 0);
919 //lua_cpp::set_functions(L, cpp_callbacks, 0);
920 lua_setglobal(L, "wesnoth");
921
922 // Create the gettext metatable.
924 // Create the tstring metatable.
926
928
929 // Override the print function
930 cmd_log_ << "Redirecting print function...\n";
931
932 lua_pushcfunction(L, intf_std_print);
933 lua_setglobal(L, "std_print");
934 lua_settop(L, 0); //clear stack, just to be sure
935
936 lua_setwarnf(L, &::impl_warn, L);
937 lua_pushcfunction(L, &dispatch<&lua_kernel_base::intf_print>);
938 lua_setglobal(L, "print");
939
940 lua_pushcfunction(L, intf_load);
941 lua_setglobal(L, "load");
942 lua_pushnil(L);
943 lua_setglobal(L, "loadstring");
944
945 // Wrap the pcall and xpcall functions
946 cmd_log_ << "Wrapping pcall and xpcall functions...\n";
947 lua_getglobal(L, "pcall");
948 lua_pushcclosure(L, intf_pcall, 1);
949 lua_setglobal(L, "pcall");
950 lua_getglobal(L, "xpcall");
951 lua_pushcclosure(L, intf_pcall, 1);
952 lua_setglobal(L, "xpcall");
953
954 cmd_log_ << "Initializing package repository...\n";
955 // Create the package table.
956 lua_getglobal(L, "wesnoth");
957 lua_newtable(L);
958 lua_setfield(L, -2, "package");
959 lua_pop(L, 1);
960 lua_settop(L, 0);
961 lua_pushstring(L, "lua/package.lua");
962 int res = intf_require(L);
963 if(res != 1) {
964 cmd_log_ << "Error: Failed to initialize package repository. Falling back to less flexible C++ implementation.\n";
965 }
966
967 // Get some callbacks for map locations
968 cmd_log_ << "Adding map table...\n";
969
970 static luaL_Reg const map_callbacks[] {
971 { "get_direction", &lua_map_location::intf_get_direction },
972 { "hex_vector_sum", &lua_map_location::intf_vector_sum },
973 { "hex_vector_diff", &lua_map_location::intf_vector_diff },
974 { "hex_vector_negation", &lua_map_location::intf_vector_negation },
975 { "rotate_right_around_center", &lua_map_location::intf_rotate_right_around_center },
976 { "are_hexes_adjacent", &lua_map_location::intf_tiles_adjacent },
977 { "get_adjacent_hexes", &lua_map_location::intf_get_adjacent_tiles },
978 { "get_hexes_in_radius", &lua_map_location::intf_get_tiles_in_radius },
979 { "get_hexes_at_radius", &lua_map_location::intf_get_tile_ring },
980 { "distance_between", &lua_map_location::intf_distance_between },
981 { "get_cubic", &lua_map_location::intf_get_in_cubic },
982 { "from_cubic", &lua_map_location::intf_get_from_cubic },
983 { "get_relative_dir", &lua_map_location::intf_get_relative_dir },
984 // Shroud bitmaps
985 {"parse_bitmap", intf_parse_shroud_bitmap},
986 {"make_bitmap", intf_make_shroud_bitmap},
987 { nullptr, nullptr }
988 };
989
990 // Create the map_location table.
991 lua_getglobal(L, "wesnoth");
992 lua_newtable(L);
993 luaL_setfuncs(L, map_callbacks, 0);
994 lua_setfield(L, -2, "map");
995 lua_pop(L, 1);
996
997 // Create the game_config variable with its metatable.
998 cmd_log_ << "Adding game_config table...\n";
999
1000 lua_getglobal(L, "wesnoth");
1001 lua_newuserdatauv(L, 0, 0);
1002 lua_createtable(L, 0, 3);
1003 lua_pushcfunction(L, &dispatch<&lua_kernel_base::impl_game_config_get>);
1004 lua_setfield(L, -2, "__index");
1005 lua_pushcfunction(L, &dispatch<&lua_kernel_base::impl_game_config_set>);
1006 lua_setfield(L, -2, "__newindex");
1007 lua_pushcfunction(L, &dispatch<&lua_kernel_base::impl_game_config_dir>);
1008 lua_setfield(L, -2, "__dir");
1009 lua_pushboolean(L, true);
1010 lua_setfield(L, -2, "__dir_tablelike");
1011 lua_pushstring(L, "game config");
1012 lua_setfield(L, -2, "__metatable");
1013 lua_setmetatable(L, -2);
1014 lua_setfield(L, -2, "game_config");
1015 lua_pop(L, 1);
1016
1017 // Add mersenne twister rng wrapper
1018 cmd_log_ << "Adding rng tables...\n";
1020
1021 cmd_log_ << "Adding name generator metatable...\n";
1022 luaL_newmetatable(L, Gen);
1023 static luaL_Reg const generator[] {
1024 { "__call", &impl_name_generator_call},
1025 { "__tostring", &impl_name_generator_tostring},
1026 { "__gc", &impl_name_generator_collect},
1027 { nullptr, nullptr}
1028 };
1029 luaL_setfuncs(L, generator, 0);
1030 lua_pushstring(L, Gen);
1031 lua_setfield(L, -2, "__metatable");
1032
1033 // Create formula bridge metatables
1035
1037
1038 // Create the Lua interpreter table
1039 cmd_log_ << "Sandboxing Lua interpreter...\nTo make variables visible outside the interpreter, assign to _G.variable.\n";
1040 cmd_log_ << "The special variable _ holds the result of the last expression (if any).\n";
1041 lua_newtable(L);
1042 lua_createtable(L, 0, 1);
1043 lua_getglobal(L, "_G");
1044 lua_setfield(L, -2, "__index");
1045 lua_setmetatable(L, -2);
1046 lua_pushcfunction(L, intf_object_dir);
1047 lua_setfield(L, -2, "dir");
1048 lua_setfield(L, LUA_REGISTRYINDEX, Interp);
1049
1050 // Loading ilua:
1051 cmd_log_ << "Loading ilua...\n";
1052
1053 lua_settop(L, 0);
1054 luaW_getglobal(L, "wesnoth", "require");
1055 lua_pushstring(L, "lua/ilua.lua");
1056 if(protected_call(1, 1)) {
1057 //run "ilua.set_strict()"
1058 lua_pushstring(L, "set_strict");
1059 lua_gettable(L, -2);
1060 if (!this->protected_call(0,0, std::bind(&lua_kernel_base::log_error, this, std::placeholders::_1, std::placeholders::_2))) {
1061 cmd_log_ << "Failed to activate strict mode.\n";
1062 } else {
1063 cmd_log_ << "Activated strict mode.\n";
1064 }
1065
1066 lua_setglobal(L, "ilua"); //save ilua table as a global
1067 } else {
1068 cmd_log_ << "Error: failed to load ilua.\n";
1069 }
1070 lua_settop(L, 0);
1071
1072 // Disable functions from debug which we don't want.
1073 // We do this last because ilua needs to be able to use debug.getmetatable
1074 lua_getglobal(L, "debug");
1075 lua_pushnil(L);
1076 while(lua_next(L, -2) != 0) {
1077 lua_pop(L, 1);
1078 char const* function = lua_tostring(L, -1);
1079 if(strcmp(function, "traceback") == 0 || strcmp(function, "getinfo") == 0) continue; //traceback is needed for our error handler
1080 lua_pushnil(L); //getinfo is needed for ilua strict mode
1081 lua_setfield(L, -3, function);
1082 }
1083 lua_pop(L, 1);
1084}
1085
1087{
1088 for (const auto& pair : this->registered_widget_definitions_) {
1089 gui2::remove_single_widget_definition(std::get<0>(pair), std::get<1>(pair));
1090 }
1091 lua_close(mState);
1092}
1093
1094void lua_kernel_base::log_error(char const * msg, char const * context)
1095{
1096 ERR_LUA << context << ": " << msg;
1097}
1098
1099void lua_kernel_base::throw_exception(char const * msg, char const * context)
1100{
1101 throw game::lua_error(msg, context);
1102}
1103
1104bool lua_kernel_base::protected_call(int nArgs, int nRets)
1105{
1106 error_handler eh = std::bind(&lua_kernel_base::log_error, this, std::placeholders::_1, std::placeholders::_2 );
1107 return this->protected_call(nArgs, nRets, eh);
1108}
1109
1110bool lua_kernel_base::load_string(char const * prog, const std::string& name)
1111{
1112 error_handler eh = std::bind(&lua_kernel_base::log_error, this, std::placeholders::_1, std::placeholders::_2 );
1113 return this->load_string(prog, name, eh);
1114}
1115
1116bool lua_kernel_base::protected_call(int nArgs, int nRets, const error_handler& e_h)
1117{
1118 return this->protected_call(mState, nArgs, nRets, e_h);
1119}
1120
1121bool lua_kernel_base::protected_call(lua_State * L, int nArgs, int nRets, const error_handler& e_h)
1122{
1123 int errcode = luaW_pcall_internal(L, nArgs, nRets);
1124
1125 if (errcode != LUA_OK) {
1126 char const * msg = lua_tostring(L, -1);
1127
1128 std::string context = "When executing, ";
1129 if (errcode == LUA_ERRRUN) {
1130 context += "Lua runtime error: ";
1131 } else if (errcode == LUA_ERRERR) {
1132 context += "Lua error in attached debugger: ";
1133 } else if (errcode == LUA_ERRMEM) {
1134 context += "Lua out of memory error: ";
1135 } else {
1136 context += "unknown lua error: ";
1137 }
1138 if(lua_isstring(L, -1)) {
1139 context += msg ? msg : "null string";
1140 } else {
1141 context += lua_typename(L, lua_type(L, -1));
1142 }
1143
1144 lua_pop(L, 1);
1145
1146 e_h(context.c_str(), "Lua Error");
1147
1148 return false;
1149 }
1150
1151 return true;
1152}
1153
1154bool lua_kernel_base::load_string(const std::string& prog, const std::string& name, const error_handler& e_h, bool allow_unsafe)
1155{
1156 // pass 't' to prevent loading bytecode which is unsafe and can be used to escape the sandbox.
1157 int errcode = luaL_loadbufferx(mState, prog.c_str(), prog.size(), name.empty() ? prog.c_str() : name.c_str(), allow_unsafe ? "tb" : "t");
1158 if (errcode != LUA_OK) {
1159 char const * msg = lua_tostring(mState, -1);
1160 std::string message = msg ? msg : "null string";
1161
1162 std::string context = "When parsing a string to lua, ";
1163
1164 if (errcode == LUA_ERRSYNTAX) {
1165 context += " a syntax error";
1166 } else if(errcode == LUA_ERRMEM){
1167 context += " a memory error";
1168 } else {
1169 context += " an unknown error";
1170 }
1171
1172 lua_pop(mState, 1);
1173
1174 e_h(message.c_str(), context.c_str());
1175
1176 return false;
1177 }
1178 return true;
1179}
1180
1182{
1183 int nArgs = 0;
1184 if (auto args = cfg.optional_child("args")) {
1185 luaW_pushconfig(this->mState, *args);
1186 ++nArgs;
1187 }
1188 this->run(cfg["code"].str().c_str(), cfg["name"].str(), nArgs);
1189}
1190
1191config luaW_serialize_function(lua_State* L, int func)
1192{
1193 if(lua_iscfunction(L, func)) {
1194 throw luafunc_serialize_error("cannot serialize C function");
1195 }
1196 if(!lua_isfunction(L, func)) {
1197 throw luafunc_serialize_error("cannot serialize callable non-function");
1198 }
1199 config data;
1200 lua_Debug info;
1201 lua_pushvalue(L, func); // push copy of function because lua_getinfo will pop it
1202 lua_getinfo(L, ">u", &info);
1203 data["params"] = info.nparams;
1204 luaW_getglobal(L, "string", "dump");
1205 lua_pushvalue(L, func);
1206 lua_call(L, 1, 1);
1207 data["code"] = lua_check<std::string>(L, -1);
1208 lua_pop(L, 1);
1209 config upvalues;
1210 for(int i = 1; i <= info.nups; i++, lua_pop(L, 1)) {
1211 std::string_view name = lua_getupvalue(L, func, i);
1212 if(name == "_ENV") {
1213 upvalues.add_child(name)["upvalue_type"] = "_ENV";
1214 continue;
1215 }
1216 int idx = lua_absindex(L, -1);
1217 switch(lua_type(L, idx)) {
1218 case LUA_TBOOLEAN: case LUA_TNUMBER: case LUA_TSTRING:
1219 luaW_toscalar(L, idx, upvalues[name]);
1220 break;
1221 case LUA_TFUNCTION:
1222 upvalues.add_child(name, luaW_serialize_function(L, idx))["upvalue_type"] = "function";
1223 break;
1224 case LUA_TNIL:
1225 upvalues.add_child(name, config{"upvalue_type", "nil"});
1226 break;
1227 case LUA_TTABLE:
1228 if(std::vector<std::string> names = luaW_to_namedtuple(L, idx); !names.empty()) {
1229 for(std::size_t i = 1; i <= lua_rawlen(L, -1); i++, lua_pop(L, 1)) {
1230 lua_rawgeti(L, idx, i);
1231 config& cfg = upvalues.add_child(name);
1232 luaW_toscalar(L, -1, cfg["value"]);
1233 cfg["name"] = names[0];
1234 cfg["upvalue_type"] = "named tuple";
1235 names.erase(names.begin());
1236 }
1237 break;
1238 } else if(config cfg; luaW_toconfig(L, idx, cfg)) {
1239 std::vector<std::string> names;
1240 int save_top = lua_gettop(L);
1241 if(luaL_getmetafield(L, idx, "__name") && lua_check<std::string>(L, -1) == "named tuple") {
1242 luaL_getmetafield(L, -2, "__names");
1243 names = lua_check<std::vector<std::string>>(L, -1);
1244 }
1245 lua_settop(L, save_top);
1246 upvalues.add_child(name, cfg)["upvalue_type"] = names.empty() ? "config" : "named tuple";
1247 break;
1248 } else {
1249 for(std::size_t i = 1; i <= lua_rawlen(L, -1); i++, lua_pop(L, 1)) {
1250 lua_rawgeti(L, idx, i);
1251 config& cfg = upvalues.add_child(name);
1252 luaW_toscalar(L, -1, cfg["value"]);
1253 cfg["upvalue_type"] = "array";
1254 }
1255 bool found_non_array = false;
1256 for(lua_pushnil(L); lua_next(L, idx); lua_pop(L, 1)) {
1257 if(lua_type(L, -2) != LUA_TNUMBER) {
1258 found_non_array = true;
1259 break;
1260 }
1261 }
1262 if(!found_non_array) break;
1263 }
1264 [[fallthrough]];
1265 default:
1266 std::ostringstream os;
1267 os << "cannot serialize function with upvalue " << name << " = ";
1268 luaW_getglobal(L, "wesnoth", "as_text");
1269 lua_pushvalue(L, idx);
1270 lua_call(L, 1, 1);
1271 os << luaL_checkstring(L, -1);
1272 lua_pushboolean(L, false);
1273 throw luafunc_serialize_error(os.str());
1274 }
1275 }
1276 if(!upvalues.empty()) data.add_child("upvalues", upvalues);
1277 return data;
1278}
1279
1281{
1282 if(!load_string(cfg["code"].str(), cfg["name"], eh, true)) return false;
1283 if(auto upvalues = cfg.optional_child("upvalues")) {
1284 lua_pushvalue(mState, -1); // duplicate function because lua_getinfo will pop it
1285 lua_Debug info;
1286 lua_getinfo(mState, ">u", &info);
1287 int funcindex = lua_absindex(mState, -1);
1288 for(int i = 1; i <= info.nups; i++) {
1289 std::string_view name = lua_getupvalue(mState, funcindex, i);
1290 lua_pop(mState, 1); // we only want the upvalue's name, not its value
1291 if(name == "_ENV") {
1292 lua_pushglobaltable(mState);
1293 } else if(upvalues->has_attribute(name)) {
1294 luaW_pushscalar(mState, (*upvalues)[name]);
1295 } else if(upvalues->has_child(name)) {
1296 const auto& child = upvalues->mandatory_child(name);
1297 if(child["upvalue_type"] == "array") {
1298 auto children = upvalues->child_range(name);
1299 lua_createtable(mState, children.size(), 0);
1300 for(const auto& cfg : children) {
1301 luaW_pushscalar(mState, cfg["value"]);
1302 lua_rawseti(mState, -2, lua_rawlen(mState, -2) + 1);
1303 }
1304 } else if(child["upvalue_type"] == "config") {
1305 luaW_pushconfig(mState, child);
1306 } else if(child["upvalue_type"] == "function") {
1307 if(!load_binary(child, eh)) return false;
1308 } else if(child["upvalue_type"] == "nil") {
1309 lua_pushnil(mState);
1310 }
1311 } else continue;
1312 lua_setupvalue(mState, funcindex, i);
1313 }
1314 }
1315 return true;
1316}
1317
1319{
1320 int top = lua_gettop(mState);
1321 try {
1322 error_handler eh = std::bind(&lua_kernel_base::throw_exception, this, std::placeholders::_1, std::placeholders::_2 );
1323 if(load_binary(cfg, eh)) {
1324 lua_pushvalue(mState, -1);
1325 protected_call(0, LUA_MULTRET, eh);
1326 }
1327 } catch (const game::lua_error & e) {
1328 cmd_log_ << e.what() << "\n";
1329 lua_kernel_base::log_error(e.what(), "In function lua_kernel::run()");
1330 config error;
1331 error["name"] = "execute_error";
1332 error["error"] = e.what();
1333 return error;
1334 }
1335 config result;
1336 result["ref"] = cfg["ref"];
1337 result.add_child("executed") = luaW_serialize_function(mState, top + 1);
1338 lua_remove(mState, top + 1);
1339 result["name"] = "execute_result";
1340 for(int i = top + 1; i < lua_gettop(mState); i++) {
1341 std::string index = std::to_string(i - top);
1342 switch(lua_type(mState, i)) {
1343 case LUA_TNUMBER: case LUA_TBOOLEAN: case LUA_TSTRING:
1344 luaW_toscalar(mState, i, result[index]);
1345 break;
1346 case LUA_TTABLE:
1347 luaW_toconfig(mState, i, result.add_child(index));
1348 break;
1349 }
1350 }
1351 return result;
1352}
1353// Call load_string and protected call. Make them throw exceptions.
1354//
1355void lua_kernel_base::throwing_run(const char * prog, const std::string& name, int nArgs, bool in_interpreter)
1356{
1357 cmd_log_ << "$ " << prog << "\n";
1358 error_handler eh = std::bind(&lua_kernel_base::throw_exception, this, std::placeholders::_1, std::placeholders::_2 );
1359 this->load_string(prog, name, eh);
1360 if(in_interpreter) {
1361 lua_getfield(mState, LUA_REGISTRYINDEX, Interp);
1362 if(lua_setupvalue(mState, -2, 1) == nullptr)
1363 lua_pop(mState, 1);
1364 }
1365 lua_insert(mState, -nArgs - 1);
1366 this->protected_call(nArgs, in_interpreter ? LUA_MULTRET : 0, eh);
1367}
1368
1369// Do a throwing run, but if we catch a lua_error, reformat it with signature for this function and log it.
1370void lua_kernel_base::run(const char * prog, const std::string& name, int nArgs)
1371{
1372 try {
1373 this->throwing_run(prog, name, nArgs);
1374 } catch (const game::lua_error & e) {
1375 cmd_log_ << e.what() << "\n";
1376 lua_kernel_base::log_error(e.what(), "In function lua_kernel::run()");
1377 }
1378}
1379
1380// Tests if a program resolves to an expression, and pretty prints it if it is, otherwise it runs it normally. Throws exceptions.
1381void lua_kernel_base::interactive_run(char const * prog) {
1382 std::string experiment = "return ";
1383 experiment += prog;
1384 int top = lua_gettop(mState);
1385
1386 error_handler eh = std::bind(&lua_kernel_base::throw_exception, this, std::placeholders::_1, std::placeholders::_2 );
1387 luaW_getglobal(mState, "ilua", "_pretty_print");
1388
1389 try {
1390 // Try to load the experiment without syntax errors
1391 this->load_string(experiment.c_str(), "interactive", eh);
1392 lua_getfield(mState, LUA_REGISTRYINDEX, Interp);
1393 if(lua_setupvalue(mState, -2, 1) == nullptr)
1394 lua_pop(mState, 1);
1395 } catch (const game::lua_error &) {
1396 this->throwing_run(prog, "interactive", 0, true); // Since it failed, fall back to the usual throwing_run, on the original input.
1397 if(lua_gettop(mState) == top + 1) {
1398 // Didn't return anything
1399 lua_settop(mState, top);
1400 return;
1401 } else goto PRINT;
1402 }
1403 // experiment succeeded, now run but log normally.
1404 cmd_log_ << "$ " << prog << "\n";
1405 this->protected_call(0, LUA_MULTRET, eh);
1406PRINT:
1407 int nRets = lua_gettop(mState) - top - 1;
1408 {
1409 // Assign first result to _
1410 lua_getfield(mState, LUA_REGISTRYINDEX, Interp);
1411 int env_idx = lua_gettop(mState);
1412 lua_pushvalue(mState, top + 2);
1413 lua_setfield(mState, -2, "_");
1414 // Now duplicate EVERY result and pass it to table.pack, assigning to _all
1415 luaW_getglobal(mState, "table", "pack");
1416 for(int i = top + 2; i < env_idx; i++)
1417 lua_pushvalue(mState, i);
1418 this->protected_call(nRets, 1, eh);
1419 lua_setfield(mState, -2, "_all");
1420 lua_pop(mState, 1);
1421 }
1422 // stack is now ilua._pretty_print followed by any results of prog
1423 this->protected_call(lua_gettop(mState) - top - 1, 0, eh);
1424}
1425/**
1426 * Loads and executes a Lua file.
1427 * - Arg 1: string containing the file name.
1428 * - Ret *: values returned by executing the file body.
1429 */
1431{
1432 luaL_checkstring(L, 1);
1433 lua_rotate(L, 1, -1);
1434 if (lua_fileops::load_file(L) != 1) return 0;
1435 //^ should end with the file contents loaded on the stack. actually it will call lua_error otherwise, the return 0 is redundant.
1436 lua_rotate(L, 1, 1);
1437 // Using a non-protected call here appears to fix an issue in plugins.
1438 // The protected call isn't technically necessary anyway, because this function is called from Lua code,
1439 // which should already be in a protected environment.
1440 lua_call(L, lua_gettop(L) - 1, LUA_MULTRET);
1441 return lua_gettop(L);
1442}
1443
1444/**
1445 * Loads and executes a Lua file, if there is no corresponding entry in wesnoth.package.
1446 * Stores the result of the script in wesnoth.package and returns it.
1447 * - Arg 1: string containing the file name.
1448 * - Ret 1: value returned by the script.
1449 */
1451{
1452 const char * m = luaL_checkstring(L, 1);
1453 if(!m) {
1454 return luaL_argerror(L, 1, "found a null string argument to wesnoth require");
1455 }
1456
1457 // Check if there is already an entry.
1458
1459 lua_getglobal(L, "wesnoth");
1460 lua_pushstring(L, "package");
1461 lua_rawget(L, -2);
1462 lua_pushvalue(L, 1);
1463 lua_rawget(L, -2);
1464 if(!lua_isnil(L, -1) && !game_config::debug_lua) {
1465 return 1;
1466 }
1467 lua_pop(L, 1);
1468 lua_pushvalue(L, 1);
1469 // stack is now [packagename] [wesnoth] [package] [packagename]
1470
1471 if(lua_fileops::load_file(L) != 1) {
1472 // should end with the file contents loaded on the stack. actually it will call lua_error otherwise, the return 0 is redundant.
1473 // stack is now [packagename] [wesnoth] [package] [chunk]
1474 return 0;
1475 }
1476 DBG_LUA << "require: loaded a file, now calling it";
1477
1478 if (!this->protected_call(L, 0, 1, std::bind(&lua_kernel_base::log_error, this, std::placeholders::_1, std::placeholders::_2))) {
1479 // historically if wesnoth.require fails it just yields nil and some logging messages, not a lua error
1480 return 0;
1481 }
1482 // stack is now [packagename] [wesnoth] [package] [results]
1483
1484 lua_pushvalue(L, 1);
1485 lua_pushvalue(L, -2);
1486 // stack is now [packagename] [wesnoth] [package] [results] [packagename] [results]
1487 // Add the return value to the table.
1488
1489 lua_settable(L, -4);
1490 // stack is now [packagename] [wesnoth] [package] [results]
1491 return 1;
1492}
1494{
1495 lua_push(L, my_name());
1496 return 1;
1497}
1498static void push_color_palette(lua_State* L, const std::vector<color_t>& palette) {
1499 static const lua_named_tuple_builder tuple_builder{ {"r", "g", "b", "a"} };
1500
1501 lua_createtable(L, palette.size(), 1);
1502 lua_rotate(L, -2, 1); // swap new table with previous element on stack
1503 lua_setfield(L, -2, "name");
1504 for(std::size_t i = 0; i < palette.size(); i++) {
1505 tuple_builder.push(L);
1506 lua_pushinteger(L, palette[i].r);
1507 lua_rawseti(L, -2, 1);
1508 lua_pushinteger(L, palette[i].g);
1509 lua_rawseti(L, -2, 2);
1510 lua_pushinteger(L, palette[i].b);
1511 lua_rawseti(L, -2, 3);
1512 lua_pushinteger(L, palette[i].a);
1513 lua_rawseti(L, -2, 4);
1514 lua_rawseti(L, -2, i);
1515 }
1516}
1517static int impl_palette_get(lua_State* L)
1518{
1519 char const *m = luaL_checkstring(L, 2);
1520 lua_pushvalue(L, 2);
1522 return 1;
1523}
1524
1525// suppress missing prototype warning (not static because game_lua_kernel referenes it);
1528 static luaW_Registry gameConfigReg{"game config"};
1529 return gameConfigReg;
1530}
1531static auto& dummy = gameConfigReg(); // just to ensure it's constructed.
1532
1533#define GAME_CONFIG_SIMPLE_GETTER(name) \
1534GAME_CONFIG_GETTER(#name, decltype(game_config::name), lua_kernel_base) { \
1535 (void) k; \
1536 return game_config::name; \
1537}
1538
1539namespace {
1540GAME_CONFIG_SIMPLE_GETTER(base_income);
1541GAME_CONFIG_SIMPLE_GETTER(village_income);
1542GAME_CONFIG_SIMPLE_GETTER(village_support);
1543GAME_CONFIG_SIMPLE_GETTER(poison_amount);
1544GAME_CONFIG_SIMPLE_GETTER(rest_heal_amount);
1545GAME_CONFIG_SIMPLE_GETTER(recall_cost);
1546GAME_CONFIG_SIMPLE_GETTER(kill_experience);
1547GAME_CONFIG_SIMPLE_GETTER(combat_experience);
1549GAME_CONFIG_SIMPLE_GETTER(debug_lua);
1550GAME_CONFIG_SIMPLE_GETTER(strict_lua);
1552
1554 (void)k;
1555 lua_newtable(L);
1556 if(luaL_newmetatable(L, "color palettes")) {
1557 lua_pushcfunction(L, impl_palette_get);
1558 lua_setfield(L, -2, "__index");
1559 lua_pushstring(L, "color palettes");
1560 lua_setfield(L, -2, "__metatable");
1561 }
1562 lua_setmetatable(L, -2);
1563 return lua_index_raw(L);
1564}
1565
1567 (void)k;
1568 lua_pushstring(L, "red_green_scale");
1570 return lua_index_raw(L);
1571}
1572
1573GAME_CONFIG_GETTER("red_green_scale_text", lua_index_raw, lua_kernel_base) {
1574 (void)k;
1575 lua_pushstring(L, "red_green_scale_text");
1577 return lua_index_raw(L);
1578}
1579
1580GAME_CONFIG_GETTER("blue_white_scale", lua_index_raw, lua_kernel_base) {
1581 (void)k;
1582 lua_pushstring(L, "blue_white_scale");
1584 return lua_index_raw(L);
1585}
1586
1587GAME_CONFIG_GETTER("blue_white_scale_text", lua_index_raw, lua_kernel_base) {
1588 (void)k;
1589 lua_pushstring(L, "blue_white_scale_text");
1591 return lua_index_raw(L);
1592}
1593}
1594
1595/**
1596 * Gets some game_config data (__index metamethod).
1597 * - Arg 1: userdata (ignored).
1598 * - Arg 2: string containing the name of the property.
1599 * - Ret 1: something containing the attribute.
1600 */
1602{
1603 return gameConfigReg().get(L);
1604}
1605/**
1606 * Sets some game_config data (__newindex metamethod).
1607 * - Arg 1: userdata (ignored).
1608 * - Arg 2: string containing the name of the property.
1609 * - Arg 3: something containing the attribute.
1610 */
1612{
1613 return gameConfigReg().set(L);
1614}
1615/**
1616 * Gets a list of game_config data (__dir metamethod).
1617 */
1619{
1620 return gameConfigReg().dir(L);
1621}
1622/**
1623 * Loads the "package" package into the Lua environment.
1624 * This action is inherently unsafe, as Lua scripts will now be able to
1625 * load C libraries on their own, hence granting them the same privileges
1626 * as the Wesnoth binary itself.
1627 */
1629{
1630 lua_State *L = mState;
1631 lua_pushcfunction(L, luaopen_package);
1632 lua_pushstring(L, "package");
1633 lua_call(L, 1, 0);
1634}
1635
1637{
1638 lua_State* L = mState;
1639 lua_settop(L, 0);
1640 cmd_log_ << "Loading core...\n";
1641 luaW_getglobal(L, "wesnoth", "require");
1642 lua_pushstring(L, "lua/core");
1643 if(!protected_call(1, 1)) {
1644 cmd_log_ << "Error: Failed to load core.\n";
1645 }
1646 lua_settop(L, 0);
1647}
1648
1649/**
1650 * Gets all the global variable names in the Lua environment. This is useful for tab completion.
1651 */
1653{
1654 std::vector<std::string> ret;
1655
1656 lua_State *L = mState;
1657
1658 int idx = lua_gettop(L);
1659 lua_getglobal(L, "_G");
1660 lua_pushnil(L);
1661
1662 while (lua_next(L, idx+1) != 0) {
1663 if (lua_isstring(L, -2)) {
1664 ret.push_back(lua_tostring(L,-2));
1665 }
1666 lua_pop(L,1);
1667 }
1668 lua_settop(L, idx);
1669 return ret;
1670}
1671
1672/**
1673 * Gets all attribute names of an extended variable name. This is useful for tab completion.
1674 */
1675std::vector<std::string> lua_kernel_base::get_attribute_names(const std::string & input)
1676{
1677 std::vector<std::string> ret;
1678 std::string base_path = input;
1679 std::size_t last_dot = base_path.find_last_of('.');
1680 std::string partial_name = base_path.substr(last_dot + 1);
1681 base_path.erase(last_dot);
1682 std::string load = "return " + base_path;
1683
1684 lua_State* L = mState;
1685 int save_stack = lua_gettop(L);
1686 int result = luaL_loadstring(L, load.c_str());
1687 if(result != LUA_OK) {
1688 // 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.
1689 LOG_LUA << "Error when attempting tab completion:";
1690 LOG_LUA << luaL_checkstring(L, -1);
1691 // Just return an empty list; no matches were found
1692 lua_settop(L, save_stack);
1693 return ret;
1694 }
1695
1696 luaW_pcall(L, 0, 1);
1697 if(lua_istable(L, -1) || lua_isuserdata(L, -1)) {
1698 int top = lua_gettop(L);
1699 int obj = lua_absindex(L, -1);
1700 if(luaL_getmetafield(L, obj, "__tab_enum") == LUA_TFUNCTION) {
1701 lua_pushvalue(L, obj);
1702 lua_pushlstring(L, partial_name.c_str(), partial_name.size());
1703 luaW_pcall(L, 2, 1);
1704 ret = lua_check<std::vector<std::string>>(L, -1);
1705 } else if(lua_type(L, -1) != LUA_TTABLE) {
1706 LOG_LUA << "Userdata missing __tab_enum meta-function for tab completion";
1707 lua_settop(L, save_stack);
1708 return ret;
1709 } else {
1710 lua_settop(L, top);
1711 // Metafunction not found, so use lua_next to enumerate the table
1712 for(lua_pushnil(L); lua_next(L, obj); lua_pop(L, 1)) {
1713 if(lua_type(L, -2) == LUA_TSTRING) {
1714 std::string attr = lua_tostring(L, -2);
1715 if(attr.empty()) {
1716 continue;
1717 }
1718 if(!utils::portable_isalpha(attr[0]) && attr[0] != '_') {
1719 continue;
1720 }
1721 if(std::any_of(attr.begin(), attr.end(), [](char c){
1722 return !utils::portable_isalpha(c) && !utils::portable_isdigit(c) && c != '_';
1723 })) {
1724 continue;
1725 }
1726 if(attr.substr(0, partial_name.size()) == partial_name) {
1727 ret.push_back(base_path + "." + attr);
1728 }
1729 }
1730 }
1731 }
1732 }
1733 lua_settop(L, save_stack);
1734 return ret;
1735}
1736
1738{
1739 #ifdef __GNUC__
1740 #pragma GCC diagnostic push
1741 #pragma GCC diagnostic ignored "-Wold-style-cast"
1742 #endif
1743 return *reinterpret_cast<lua_kernel_base**>(lua_getextraspace(L));
1744 #ifdef __GNUC__
1745 #pragma GCC diagnostic pop
1746 #endif
1747}
1748
1750{
1751 return seed_rng::next_seed();
1752}
map_location loc
Definition move.cpp:172
luaW_Registry & gameConfigReg()
#define ERR_LUA
#define LOG_LUA
double t
#define debug(x)
std::vector< std::string > names
A config object defines a single node in a WML file, with access to child nodes.
Definition config.hpp:157
config & add_child(std::string_view key)
Definition config.cpp:428
all_children_iterator erase(const all_children_iterator &i)
Definition config.cpp:610
optional_config_impl< config > optional_child(std::string_view key, int n=0)
Equivalent to mandatory_child, but returns an empty optional if the nth child was not found.
Definition config.cpp:372
bool empty() const
Definition config.cpp:815
static void rethrow()
Rethrows the stored exception.
void load_core()
Loads the "core" library into the Lua environment.
void run(char const *prog, const std::string &name, int nArgs=0)
Runs a plain script.
virtual void log_error(char const *msg, char const *context="Lua error")
Error reporting mechanisms, used by virtual methods protected_call and load_string.
int intf_dofile(lua_State *L)
Loads and executes a Lua file.
int impl_game_config_get(lua_State *L)
Gets some game_config data (__index metamethod).
int intf_require(lua_State *L)
Loads and executes a Lua file, if there is no corresponding entry in wesnoth.package.
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.
int intf_kernel_type(lua_State *L)
int impl_game_config_set(lua_State *L)
Sets some game_config data (__newindex metamethod).
void load_package()
Loads the package library into lua environment.
bool protected_call(int nArgs, int nRets, const error_handler &)
void add_log_to_console(const std::string &msg)
int impl_game_config_dir(lua_State *L)
Gets a list of game_config data (__dir metamethod).
int intf_show_lua_console(lua_State *L)
bool load_string(const std::string &prog, const std::string &name, const error_handler &, bool allow_unsafe=false)
std::vector< std::tuple< std::string, std::string > > registered_widget_definitions_
static lua_kernel_base *& get_lua_kernel_base_ptr(lua_State *L)
std::vector< std::string > get_global_var_names()
Get tab completion strings.
std::function< void(char const *, char const *)> error_handler
void run_lua_tag(const config &cfg)
Runs a [lua] tag.
bool load_binary(const config &func, const error_handler &)
int intf_print(lua_State *L)
Replacement print function – instead of printing to std::cout, print to the command log.
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...
std::vector< std::string > get_attribute_names(const std::string &var_path)
Gets all attribute names of an extended variable name.
config run_binary_lua_tag(const config &cfg)
Runs a binary [lua] tag.
virtual uint32_t get_random_seed()
virtual void throw_exception(char const *msg, char const *context="Lua error")
virtual std::string my_name()
User-visible name of the lua kernel that they are talking to.
Efficiently creates new LUA "named tuples" with the specified field names.
void push(lua_State *L) const
Push an empty "named tuple" onto the stack.
const char * what() const noexcept
std::string generate(const std::map< std::string, std::string > &variables) const
virtual ~name_generator()
virtual std::string type() const
int height() const
Definition team.cpp:756
void read(const std::string &shroud_data)
Definition team.cpp:871
void set_enabled(bool enabled)
Definition team.hpp:60
int width() const
Definition team.cpp:751
bool value(int x, int y) const
Definition team.cpp:814
std::string write() const
Definition team.cpp:855
bool clear(int x, int y)
Definition team.cpp:764
const std::string & str() const
Definition tstring.hpp:204
Represents version numbers.
std::string str() const
Serializes the version number into string form.
unsigned int revision_level() const
Retrieves the revision level (x3 in "x1.x2.x3").
char special_version_separator() const
Retrieves the special version separator (e.g.
const std::string & special_version() const
Retrieves the special version suffix (e.g.
unsigned int minor_version() const
Retrieves the minor version number (x2 in "x1.x2.x3").
const std::vector< unsigned int > & components() const
Read-only access to all numeric components.
unsigned int major_version() const
Retrieves the major version number (x1 in "x1.x2.x3").
bool is_canonical() const
Whether the version number is considered canonical for mainline Wesnoth.
std::string deprecated_message(const std::string &elem_name, DEP_LEVEL level, const version_info &version, const std::string &detail)
DEP_LEVEL
See https://wiki.wesnoth.org/CompatibilityStandards for more info.
const config * cfg
int(* lua_CFunction)(lua_State *L)
bool do_version_check(const version_info &a, VERSION_COMP_OP op, const version_info &b)
Interfaces for manipulating version numbers of engine, add-ons, etc.
const language_def & get_language()
Definition language.cpp:317
Standard logging facilities (interface).
#define LOG_STREAM(level, domain)
Definition log.hpp:278
void luaW_pushconfig(lua_State *L, const config &cfg)
Converts a config object to a Lua table pushed at the top of the stack.
int luaW_pcall_internal(lua_State *L, int nArgs, int nRets)
void push_error_handler(lua_State *L)
bool luaW_toboolean(lua_State *L, int n)
int luaW_type_error(lua_State *L, int narg, const char *tname)
bool luaW_toscalar(lua_State *L, int index, config::attribute_value &v)
Converts the value at the top of the stack to an attribute value.
void luaW_pushscalar(lua_State *L, const config::attribute_value &v)
Converts an attribute value into a Lua object pushed at the top of the stack.
std::vector< std::string > luaW_to_namedtuple(lua_State *L, int idx)
Get the keys of a "named tuple" from the stack.
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.
bool luaW_toconfig(lua_State *L, int index, config &cfg)
Converts an optional table or vconfig to a config object.
int luaW_push_locationset(lua_State *L, const std::set< map_location > &locs)
Converts a set of map locations to a Lua table pushed at the top of the stack.
std::set< map_location > luaW_check_locationset(lua_State *L, int idx)
Converts a table of integer pairs to a set of map location objects.
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.
t_string luaW_checktstring(lua_State *L, int index)
Converts a scalar to a translatable string.
#define return_string_attrib(name, accessor)
#define return_int_attrib(name, accessor)
#define return_bool_attrib(name, accessor)
#define DBG_LUA
static int intf_make_shroud_bitmap(lua_State *L)
static int impl_version_finalize(lua_State *L)
Destroy a version.
int dispatch(lua_State *L)
static int intf_name_generator(lua_State *L)
static lg::log_domain log_user("scripting/lua/user")
static int intf_current_version(lua_State *L)
Returns the current Wesnoth version.
static lg::log_domain log_scripting_lua("scripting/lua")
static int intf_parse_shroud_bitmap(lua_State *L)
static int intf_make_version(lua_State *L)
Builds a version from its component parts, or parses it from a string.
static int impl_version_dir(lua_State *L)
static int impl_version_get(lua_State *L)
Decomposes a version into its component parts.
static int impl_get_dir_suffix(lua_State *L)
static int impl_version_tostring(lua_State *L)
Convert a version to string form.
static int intf_deprecated_message(lua_State *L)
Logs a deprecation message.
static int intf_pcall(lua_State *L)
Wrapper for pcall and xpcall functions to rethrow jailbreak exceptions.
static int intf_named_tuple(lua_State *L)
Converts a Lua array to a named tuple.
std::vector< std::string > luaW_get_attributes(lua_State *L, int idx)
This function does the actual work of grabbing all the attribute names.
static void impl_warn(void *p, const char *msg, int tocont)
int(lua_kernel_base::* member_callback)(lua_State *L)
static const char * Version
static int intf_log(lua_State *L)
Logs a message Arg 1: (optional) Logger Arg 2: Message.
static int impl_palette_get(lua_State *L)
static auto & dummy
static int impl_is_deprecated(lua_State *L)
static const char * Interp
static void push_color_palette(lua_State *L, const std::vector< color_t > &palette)
static int intf_std_print(lua_State *L)
static int intf_load(lua_State *L)
Replacement load function.
static int intf_ms_since_init(lua_State *L)
Returns the time stamp, exactly as [set_variable] time=stamp does.
static const char * Gen
static int intf_get_language(lua_State *L)
static int impl_name_generator_call(lua_State *L)
static int impl_name_generator_tostring(lua_State *L)
luaW_Registry & gameConfigReg()
static void dir_meta_helper(lua_State *L, std::vector< std::string > &keys)
static int intf_object_dir(lua_State *L)
Prints out a list of keys available in an object.
static int intf_safe_tostring(lua_State *L)
#define GAME_CONFIG_SIMPLE_GETTER(name)
config luaW_serialize_function(lua_State *L, int func)
static int impl_name_generator_collect(lua_State *L)
static int impl_version_compare(lua_State *L)
Compares two versions.
config luaW_serialize_function(lua_State *L, int func)
#define GAME_CONFIG_GETTER(name, type, kernel_type)
std::vector< color_t > red_green_scale_text
const version_info wesnoth_version(VERSION)
const std::vector< color_t > & tc_info(std::string_view name)
std::vector< color_t > blue_white_scale
std::vector< color_t > red_green_scale
std::vector< color_t > blue_white_scale_text
void remove_single_widget_definition(const std::string &widget_type, const std::string &definition_id)
Removes a widget definition from the default GUI.
std::string register_metatables(lua_State *L)
int intf_textdomain(lua_State *L)
Creates an interface for gettext.
std::string register_gettext_metatable(lua_State *L)
Adds the gettext metatable.
std::string register_tstring_metatable(lua_State *L)
Adds the tstring metatable.
void register_metatable(lua_State *L)
int luaW_open(lua_State *L)
int load_file(lua_State *L)
Loads a Lua file and pushes the contents on the stack.
std::string register_metatables(lua_State *)
int intf_compile_formula(lua_State *)
int intf_eval_formula(lua_State *)
Evaluates a formula in the formula engine.
int luaW_open(lua_State *L)
Definition lua_gui2.cpp:398
int show_lua_console(lua_State *, lua_kernel_base *lk)
Definition lua_gui2.cpp:250
int intf_get_relative_dir(lua_State *L)
Expose map_location get_relative_dir.
int intf_vector_negation(lua_State *L)
Expose map_location::vector_negation to lua.
int intf_distance_between(lua_State *L)
Expose map_location distance_between.
int intf_get_in_cubic(lua_State *L)
Expose map_location to_cubic.
int intf_tiles_adjacent(lua_State *L)
Expose map_location tiles_adjacent.
int intf_vector_diff(lua_State *L)
Expose map_location::vector_difference to lua.
int intf_get_from_cubic(lua_State *L)
Expose map_location from_cubic.
int intf_vector_sum(lua_State *L)
Expose map_location::vector_sum to lua.
int intf_get_tile_ring(lua_State *L)
Expose map_location get_tile_ring.
int intf_rotate_right_around_center(lua_State *L)
Expose map_location::rotate_right_around_center to lua.
int intf_get_tiles_in_radius(lua_State *L)
Expose map_location get_tiles_in_radius.
int intf_get_adjacent_tiles(lua_State *L)
Expose map_location get_adjacent_tiles.
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...
int luaW_open(lua_State *L)
Definition lua_mathx.cpp:61
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:97
int luaW_open(lua_State *L)
void register_metatable(lua_State *L)
int luaW_open(lua_State *L)
Definition lua_wml.cpp:240
uint32_t next_seed()
Definition seed_rng.cpp:32
constexpr auto keys
Definition ranges.hpp:43
std::vector< std::string > parenthetical_split(std::string_view val, const char separator, std::string_view left, std::string_view right, const int flags)
Splits a string based either on a separator, except then the text appears within specified parenthesi...
constexpr bool portable_isalpha(int c)
std::vector< std::string > split(const config_attribute_value &val)
std::string_view data
Definition picture.cpp:188
void lua_push(lua_State *L, const T &val)
#define ON_SCOPE_EXIT(...)
Run some arbitrary code (a lambda) when the current scope exits The lambda body follows this header,...
Error used to report an error in a lua script or in the lua interpreter.
Holds a lookup table for members of one type of object.
int dir(lua_State *L)
Implement __dir metamethod.
int set(lua_State *L)
Implement __newindex metamethod.
int get(lua_State *L)
Implement __index metamethod.
int wml_y() const
Definition location.hpp:187
int wml_x() const
Definition location.hpp:186
mock_party p
static map_location::direction n
#define i
#define g
#define e
#define c
#define b