For consistency, rename tstr:format -> tstr:vformat, and add tstr:format as an alias to string.format

In order for the latter to work, string.format was overridden as follows (but implemented in the C API):

local old_format = string.format
function string.format(str, ...)
	if type(str) == 'userdata' and getmetatable(str) == 'translatable string' then str = tostring(str) end
	return old_format(str, ...)
end
This commit is contained in:
Celtic Minstrel 2019-12-04 22:28:14 -05:00
parent 0b433d7ca1
commit 30240aa7cd
2 changed files with 31 additions and 1 deletions

View file

@ -444,8 +444,10 @@ std::string register_tstring_metatable(lua_State *L)
luaL_setfuncs(L, callbacks, 0); luaL_setfuncs(L, callbacks, 0);
lua_createtable(L, 0, 1); lua_createtable(L, 0, 1);
luaW_getglobal(L, "stringx", "vformat"); luaW_getglobal(L, "string", "format");
lua_setfield(L, -2, "format"); lua_setfield(L, -2, "format");
luaW_getglobal(L, "stringx", "vformat");
lua_setfield(L, -2, "vformat");
lua_setfield(L, -2, "__index"); lua_setfield(L, -2, "__index");
lua_pushstring(L, "translatable string"); lua_pushstring(L, "translatable string");

View file

@ -720,6 +720,27 @@ static int intf_str_trim(lua_State* L)
return 1; return 1;
} }
// Override string.format to coerce the format to a string
static int intf_str_format(lua_State* L)
{
int nargs = lua_gettop(L);
if(luaW_iststring(L, 1)) {
// get the tostring() function and call it on the first argument
lua_getglobal(L, "tostring");
lua_pushvalue(L, 1);
lua_call(L, 1, 1);
// replace the first argument with the coerced value
lua_replace(L, 1);
}
// grab the original string.format function from the closure...
lua_pushvalue(L, lua_upvalueindex(1));
// ...move it to the bottom of the stack...
lua_insert(L, 1);
// ...and finally pass along all the arguments to it.
lua_call(L, nargs, 1);
return 1;
}
/** /**
* Parses a range string of the form a-b into an interval pair * Parses a range string of the form a-b into an interval pair
* Accepts the string "infinity" as representing a Very Large Number * Accepts the string "infinity" as representing a Very Large Number
@ -1003,6 +1024,13 @@ lua_kernel_base::lua_kernel_base()
lua_setfield(L, -2, "__index"); lua_setfield(L, -2, "__index");
lua_setmetatable(L, -2); lua_setmetatable(L, -2);
// Override string.format
lua_getglobal(L, "string");
lua_getfield(L, -1, "format");
lua_pushcclosure(L, &intf_str_format, 1);
lua_setfield(L, -2, "format");
lua_pop(L, 1);
// Create the gettext metatable. // Create the gettext metatable.
cmd_log_ << lua_common::register_gettext_metatable(L); cmd_log_ << lua_common::register_gettext_metatable(L);
// Create the tstring metatable. // Create the tstring metatable.