56#include <SDL3/SDL_timer.h>
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)
74static const char *
Gen =
"name generator";
77static const char *
Interp =
"lua interpreter";
86template<VERSION_COMP_OP vop>
92 lua_pushboolean(L, result);
102 if(lua_isinteger(L, 2)) {
103 int n = lua_tointeger(L, 2) - 1;
105 if(
n >= 0 && std::size_t(
n) < components.size()) {
112 char const *m = luaL_checkstring(L, 2);
120 }
else if(strcmp(m,
"sep") == 0) {
129 static const std::vector<std::string> fields{
"major",
"minor",
"revision",
"is_canonical",
"special",
"sep"};
140 vers->~version_info();
160 if(luaL_testudata(L, 1,
Version)) {
166 if(lua_type(L, 1) == LUA_TSTRING) {
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);
176 sep.push_back(special[0]);
177 special = special.substr(1);
182 new(L)
version_info(major, minor, rev, sep[0], special);
184 if(luaL_newmetatable(L,
Version)) {
185 static const luaL_Reg metafuncs[] {
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> },
195 luaL_setfuncs(L, metafuncs, 0);
196 luaW_table_set<std::string>(L, -1,
"__metatable",
Version);
198 lua_setmetatable(L, -2);
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) {
229 luaL_tolstring(L, 1,
nullptr);
234 const int name_type = luaL_getmetafield(L, 1,
"__name");
235 if(name_type == LUA_TSTRING) {
238 if(name_type != LUA_TNIL) {
241 lua_pushstring(L, luaL_typename(L, 1));
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);
256 const int status = lua_pcall(L, 1, 1, 0);
259 if(status != LUA_OK) {
263 std::size_t length = 0;
264 const char*
string = luaL_checklstring(L, -1, &length);
266 lua_writestring(
"\t", 1);
268 lua_writestring(
string, length);
282 DBG_LUA <<
"intf_print called:";
283 std::size_t nargs = lua_gettop(L);
285 lua_getglobal(L,
"tostring");
286 for (std::size_t
i = 1;
i <= nargs; ++
i) {
287 lua_pushvalue(L, -1);
290 const char * str = lua_tostring(L, -1);
292 LOG_LUA <<
"'tostring' must return a value to 'print'";
311 static const char*
const prefix =
"Warning:\n ";
312 static std::ostringstream warning(prefix);
313 warning.seekp(0, std::ios::end);
314 warning << msg <<
' ';
316 auto L =
reinterpret_cast<lua_State*
>(
p);
319 lua_pushinteger(L, 2);
321 auto& lk = lua_kernel_base::get_lua_kernel<lua_kernel_base>(L);
322 lk.add_log_to_console(luaL_checkstring(L, -1));
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);
344 return luaL_argerror(L, 3,
"binary chunks are not allowed for security reasons");
347 int result = luaL_loadbufferx(L, chunk.data(), chunk.length(), name,
"t");
348 if(result != LUA_OK) {
360 const char* upvalue_name = lua_setupvalue(L, -2, 1);
361 if(upvalue_name ==
nullptr) {
375 lua_CFunction function = lua_tocfunction(L, lua_upvalueindex(1));
378 int nRets = function(L);
390 std::string message =
"There is already an external logger attached to this lua kernel, you cannot open the lua console right now.";
402 lua_pushstring(L, gen->
generate().c_str());
410 lua_pushstring(L,
"%s: %s");
411 lua_pushstring(L,
Gen);
412 lua_pushstring(L, gen->
type().c_str());
426 std::string type = luaL_checkstring(L, 1);
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);
436 int chain_sz = luaL_optinteger(L, 3, 2);
437 int max_len = luaL_optinteger(L, 4, 12);
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)");
449 if(lua_isstring(L, -1)) {
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");
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));
459 lua_pushstring(L,
"CFG generator: invalid nonterminal value (must be a string or list of strings)");
473 return luaL_argerror(L, 1,
"should be either 'markov_chain' or 'context_free'");
477 lua_pushstring(L, ex.
what());
483 luaL_getmetatable(L,
Gen);
484 lua_setmetatable(L, -2);
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') {
501 if(logger ==
"err" || logger ==
"error") {
503 }
else if(logger ==
"warn" || logger ==
"wrn" || logger ==
"warning") {
505 }
else if((logger ==
"debug" || logger ==
"dbg")) {
521 const std::string elem = luaL_checkstring(L, 1);
524 const std::string ver_str = lua_isnoneornil(L, 3) ?
"" : luaL_checkstring(L, 3);
533 lua_warning(L, msg.c_str(),
false);
548 if(!lua_istable(L, 1)) {
551 auto names = lua_check<std::vector<std::string>>(L, 2);
553 int len = luaL_checkinteger(L, -1);
555 for(
int i = 1; i <= std::max<int>(len,
names.size());
i++) {
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)) {
584 for(
const auto&
loc : locs) {
596 lua_pushinteger(L, SDL_GetTicks());
608 switch(luaL_getmetafield(L, -1,
"__dir")) {
612 if(lua_pcall(L, 2, 1, 0) == LUA_OK) {
613 keys = lua_check<std::vector<std::string>>(L, -1);
615 lua_warning(L,
"wesnoth.print_attributes: __dir metamethod raised an error",
false);
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));
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) {
635 lua_pushboolean(L, deprecated);
640 lua_pushboolean(L,
false);
647 auto key = luaL_checkstring(L, 2);
648 std::string suffix =
" ";
649 auto type = lua_getfield(L, 1, key);
650 if(type == LUA_TTABLE) {
652 }
else if(type == LUA_TFUNCTION) {
654 }
else if(type == LUA_TUSERDATA) {
655 lua_getglobal(L,
"getmetatable");
656 lua_pushvalue(L, -2);
658 if(lua_type(L, -1) == LUA_TSTRING) {
659 auto meta = lua_check<std::string>(L, -1);
660 if(meta ==
"function") {
665 if(suffix.size() == 1) {
667 if(
auto t = luaL_getmetafield(L, -1,
"__dir_tablelike");
t == LUA_TBOOLEAN) {
672 }
else if(
t != LUA_TNIL) {
677 suffix =
" " + suffix;
678 lua_pushlstring(L, suffix.c_str(), suffix.size());
688 if(idx < 0 && idx >= -lua_gettop(L)) {
689 idx = lua_absindex(L, idx);
691 std::vector<std::string> keys;
692 if(lua_istable(L, idx)) {
695 int save_top = lua_gettop(L);
696 lua_pushvalue(L, idx);
698 lua_settop(L, save_top);
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));
712 if(luaL_getmetafield(L, table_idx,
"__index") == LUA_TNIL)
break;
713 }
while(lua_istable(L, -1));
714 if(lua_isfunction(L, -1)) {
718 }
else if(lua_isuserdata(L, idx) && !lua_islightuserdata(L, idx)) {
719 lua_pushvalue(L, idx);
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) {
730 int save_top = lua_gettop(L);
732 lua_settop(L, save_top);
739 lua_pushvalue(L, idx);
741 if(lua_pcall(L, 2, 1, 0) == LUA_OK) {
764 if(lua_isnil(L, 1))
return luaL_argerror(L, 1,
"Can't dir() nil");
765 if(!lua_isfunction(L, 2)) {
768 int fcn_idx = lua_gettop(L);
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());
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;
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);
785 lua_settop(L, save_top);
789 const auto& key = keys[j +
i * n_cols];
790 lua_pushlstring(L, key.c_str(), key.size());
791 std::string suffix =
" !";
792 if(lua_pcall(L, 2, 1, 0) == LUA_OK) {
793 suffix = luaL_checkstring(L, -1);
797 line.width(col_width - SUFFIX_PADDING + suffix.size());
799 line << (key + suffix) << std::flush;
801 lua_pushvalue(L, fcn_idx);
813template <member_callback method>
815 return ((lua_kernel_base::get_lua_kernel<lua_kernel_base>(L)).*method)(L);
820 : mState(luaL_newstate())
830 cmd_log_ <<
"Adding boost function proxy...\n";
836 cmd_log_ <<
"Adding standard libs...\n";
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 },
855 for (luaL_Reg
const *lib = safe_libs; lib->func; ++lib)
857 luaL_requiref(L, lib->name, lib->func, strlen(lib->name));
864 lua_setglobal(L,
"tostring");
867 lua_getglobal(L,
"os");
869 while(lua_next(L, -2) != 0) {
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;
875 lua_setfield(L, -3, function);
881 lua_setglobal(L,
"dofile");
883 lua_setglobal(L,
"loadfile");
886 cmd_log_ <<
"Adding error handler...\n";
893 cmd_log_ <<
"Registering basic wesnoth API...\n";
895 static luaL_Reg
const callbacks[] {
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> },
914 lua_getglobal(L,
"wesnoth");
915 if (!lua_istable(L,-1)) {
918 luaL_setfuncs(L, callbacks, 0);
920 lua_setglobal(L,
"wesnoth");
930 cmd_log_ <<
"Redirecting print function...\n";
933 lua_setglobal(L,
"std_print");
937 lua_pushcfunction(L, &dispatch<&lua_kernel_base::intf_print>);
938 lua_setglobal(L,
"print");
941 lua_setglobal(L,
"load");
943 lua_setglobal(L,
"loadstring");
946 cmd_log_ <<
"Wrapping pcall and xpcall functions...\n";
947 lua_getglobal(L,
"pcall");
949 lua_setglobal(L,
"pcall");
950 lua_getglobal(L,
"xpcall");
952 lua_setglobal(L,
"xpcall");
954 cmd_log_ <<
"Initializing package repository...\n";
956 lua_getglobal(L,
"wesnoth");
958 lua_setfield(L, -2,
"package");
961 lua_pushstring(L,
"lua/package.lua");
964 cmd_log_ <<
"Error: Failed to initialize package repository. Falling back to less flexible C++ implementation.\n";
968 cmd_log_ <<
"Adding map table...\n";
970 static luaL_Reg
const map_callbacks[] {
991 lua_getglobal(L,
"wesnoth");
993 luaL_setfuncs(L, map_callbacks, 0);
994 lua_setfield(L, -2,
"map");
998 cmd_log_ <<
"Adding game_config table...\n";
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");
1018 cmd_log_ <<
"Adding rng tables...\n";
1021 cmd_log_ <<
"Adding name generator metatable...\n";
1022 luaL_newmetatable(L,
Gen);
1023 static luaL_Reg
const generator[] {
1029 luaL_setfuncs(L, generator, 0);
1030 lua_pushstring(L,
Gen);
1031 lua_setfield(L, -2,
"__metatable");
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";
1042 lua_createtable(L, 0, 1);
1043 lua_getglobal(L,
"_G");
1044 lua_setfield(L, -2,
"__index");
1045 lua_setmetatable(L, -2);
1047 lua_setfield(L, -2,
"dir");
1048 lua_setfield(L, LUA_REGISTRYINDEX,
Interp);
1055 lua_pushstring(L,
"lua/ilua.lua");
1058 lua_pushstring(L,
"set_strict");
1059 lua_gettable(L, -2);
1061 cmd_log_ <<
"Failed to activate strict mode.\n";
1063 cmd_log_ <<
"Activated strict mode.\n";
1066 lua_setglobal(L,
"ilua");
1068 cmd_log_ <<
"Error: failed to load ilua.\n";
1074 lua_getglobal(L,
"debug");
1076 while(lua_next(L, -2) != 0) {
1078 char const* function = lua_tostring(L, -1);
1079 if(strcmp(function,
"traceback") == 0 || strcmp(function,
"getinfo") == 0)
continue;
1081 lua_setfield(L, -3, function);
1096 ERR_LUA << context <<
": " << msg;
1125 if (errcode != LUA_OK) {
1126 char const * msg = lua_tostring(L, -1);
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: ";
1136 context +=
"unknown lua error: ";
1138 if(lua_isstring(L, -1)) {
1139 context += msg ? msg :
"null string";
1141 context += lua_typename(L, lua_type(L, -1));
1146 e_h(context.c_str(),
"Lua Error");
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";
1162 std::string context =
"When parsing a string to lua, ";
1164 if (errcode == LUA_ERRSYNTAX) {
1165 context +=
" a syntax error";
1166 }
else if(errcode == LUA_ERRMEM){
1167 context +=
" a memory error";
1169 context +=
" an unknown error";
1174 e_h(message.c_str(), context.c_str());
1188 this->
run(cfg[
"code"].str().c_str(),
cfg[
"name"].str(), nArgs);
1193 if(lua_iscfunction(L, func)) {
1196 if(!lua_isfunction(L, func)) {
1201 lua_pushvalue(L, func);
1202 lua_getinfo(L,
">u", &info);
1203 data[
"params"] = info.nparams;
1205 lua_pushvalue(L, func);
1207 data[
"code"] = lua_check<std::string>(L, -1);
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";
1216 int idx = lua_absindex(L, -1);
1217 switch(lua_type(L, idx)) {
1218 case LUA_TBOOLEAN:
case LUA_TNUMBER:
case LUA_TSTRING:
1229 for(std::size_t
i = 1;
i <= lua_rawlen(L, -1);
i++, lua_pop(L, 1)) {
1230 lua_rawgeti(L, idx,
i);
1234 cfg[
"upvalue_type"] =
"named tuple";
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);
1245 lua_settop(L, save_top);
1249 for(std::size_t
i = 1;
i <= lua_rawlen(L, -1);
i++, lua_pop(L, 1)) {
1250 lua_rawgeti(L, idx,
i);
1253 cfg[
"upvalue_type"] =
"array";
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;
1262 if(!found_non_array)
break;
1266 std::ostringstream os;
1267 os <<
"cannot serialize function with upvalue " << name <<
" = ";
1269 lua_pushvalue(L, idx);
1271 os << luaL_checkstring(L, -1);
1272 lua_pushboolean(L,
false);
1276 if(!upvalues.
empty())
data.add_child(
"upvalues", upvalues);
1284 lua_pushvalue(
mState, -1);
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);
1291 if(name ==
"_ENV") {
1292 lua_pushglobaltable(
mState);
1293 }
else if(upvalues->has_attribute(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) {
1304 }
else if(child[
"upvalue_type"] ==
"config") {
1306 }
else if(child[
"upvalue_type"] ==
"function") {
1308 }
else if(child[
"upvalue_type"] ==
"nil") {
1312 lua_setupvalue(
mState, funcindex,
i);
1320 int top = lua_gettop(
mState);
1324 lua_pushvalue(
mState, -1);
1331 error[
"name"] =
"execute_error";
1332 error[
"error"] =
e.what();
1336 result[
"ref"] =
cfg[
"ref"];
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);
1343 case LUA_TNUMBER:
case LUA_TBOOLEAN:
case LUA_TSTRING:
1360 if(in_interpreter) {
1362 if(lua_setupvalue(
mState, -2, 1) ==
nullptr)
1365 lua_insert(
mState, -nArgs - 1);
1366 this->
protected_call(nArgs, in_interpreter ? LUA_MULTRET : 0, eh);
1382 std::string experiment =
"return ";
1384 int top = lua_gettop(
mState);
1391 this->
load_string(experiment.c_str(),
"interactive", eh);
1393 if(lua_setupvalue(
mState, -2, 1) ==
nullptr)
1397 if(lua_gettop(
mState) == top + 1) {
1407 int nRets = lua_gettop(
mState) - top - 1;
1411 int env_idx = lua_gettop(
mState);
1412 lua_pushvalue(
mState, top + 2);
1413 lua_setfield(
mState, -2,
"_");
1416 for(
int i = top + 2;
i < env_idx;
i++)
1419 lua_setfield(
mState, -2,
"_all");
1432 luaL_checkstring(L, 1);
1433 lua_rotate(L, 1, -1);
1436 lua_rotate(L, 1, 1);
1440 lua_call(L, lua_gettop(L) - 1, LUA_MULTRET);
1441 return lua_gettop(L);
1452 const char * m = luaL_checkstring(L, 1);
1454 return luaL_argerror(L, 1,
"found a null string argument to wesnoth require");
1459 lua_getglobal(L,
"wesnoth");
1460 lua_pushstring(L,
"package");
1462 lua_pushvalue(L, 1);
1468 lua_pushvalue(L, 1);
1476 DBG_LUA <<
"require: loaded a file, now calling it";
1484 lua_pushvalue(L, 1);
1485 lua_pushvalue(L, -2);
1489 lua_settable(L, -4);
1501 lua_createtable(L, palette.size(), 1);
1502 lua_rotate(L, -2, 1);
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);
1519 char const *m = luaL_checkstring(L, 2);
1520 lua_pushvalue(L, 2);
1533#define GAME_CONFIG_SIMPLE_GETTER(name) \
1534GAME_CONFIG_GETTER(#name, decltype(game_config::name), lua_kernel_base) { \
1536 return game_config::name; \
1556 if(luaL_newmetatable(L,
"color palettes")) {
1558 lua_setfield(L, -2,
"__index");
1559 lua_pushstring(L,
"color palettes");
1560 lua_setfield(L, -2,
"__metatable");
1562 lua_setmetatable(L, -2);
1568 lua_pushstring(L,
"red_green_scale");
1575 lua_pushstring(L,
"red_green_scale_text");
1582 lua_pushstring(L,
"blue_white_scale");
1589 lua_pushstring(L,
"blue_white_scale_text");
1631 lua_pushcfunction(L, luaopen_package);
1632 lua_pushstring(L,
"package");
1642 lua_pushstring(L,
"lua/core");
1644 cmd_log_ <<
"Error: Failed to load core.\n";
1654 std::vector<std::string> ret;
1658 int idx = lua_gettop(L);
1659 lua_getglobal(L,
"_G");
1662 while (lua_next(L, idx+1) != 0) {
1663 if (lua_isstring(L, -2)) {
1664 ret.push_back(lua_tostring(L,-2));
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;
1685 int save_stack = lua_gettop(L);
1686 int result = luaL_loadstring(L, load.c_str());
1687 if(result != LUA_OK) {
1689 LOG_LUA <<
"Error when attempting tab completion:";
1690 LOG_LUA << luaL_checkstring(L, -1);
1692 lua_settop(L, save_stack);
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());
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);
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);
1721 if(std::any_of(attr.begin(), attr.end(), [](
char c){
1722 return !utils::portable_isalpha(c) && !utils::portable_isdigit(c) && c !=
'_';
1726 if(attr.substr(0, partial_name.size()) == partial_name) {
1727 ret.push_back(base_path +
"." + attr);
1733 lua_settop(L, save_stack);
1740 #pragma GCC diagnostic push
1741 #pragma GCC diagnostic ignored "-Wold-style-cast"
1745 #pragma GCC diagnostic pop
luaW_Registry & gameConfigReg()
std::vector< std::string > names
A config object defines a single node in a WML file, with access to child nodes.
config & add_child(std::string_view key)
all_children_iterator erase(const all_children_iterator &i)
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.
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 &)
virtual ~lua_kernel_base()
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
void read(const std::string &shroud_data)
void set_enabled(bool enabled)
bool value(int x, int y) const
std::string write() const
const std::string & str() const
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.
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()
Standard logging facilities (interface).
#define LOG_STREAM(level, domain)
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)
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 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 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.
int luaW_open(lua_State *L)
int show_lua_console(lua_State *, lua_kernel_base *lk)
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)
void load_tables(lua_State *L)
Creates the metatable for RNG objects, and adds the Rng table which contains the constructor.
int luaW_open(lua_State *L)
int luaW_open(lua_State *L)
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)
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.
external_log_type external_log_
static map_location::direction n