Skip to content

Commit

Permalink
MetaData: restore undocumented set_string behaviour
Browse files Browse the repository at this point in the history
  • Loading branch information
SmallJoker committed Feb 22, 2024
1 parent e3cc26c commit 610c9cd
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
27 changes: 26 additions & 1 deletion games/devtest/mods/unittests/metadata.lua
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,29 @@ local function test_metadata(meta)
assert(not meta:equals(compare_meta))
end

local function test_metadata_compat(meta)
-- key/value removal using set_string (undocumented, deprecated way)
meta:set_string("key", "value")
assert(meta:get_string("key") == "value")
meta:set_string("key", nil) -- ignore warning
assert(meta:to_table().fields["key"] == nil)

-- undocumented but supported consequence of Lua's
-- automatic string <--> number cast
meta:set_string("key", 2)
assert(meta:get_string("key") == "2")

-- from_table with non-string keys (supported)
local values = meta:to_table()
values.fields["new"] = 420
meta:from_table(values)
assert(meta:get_int("new") == 420)
values.fields["new"] = nil
meta:from_table(values)
assert(meta:get("new") == nil)
end


local storage_a = core.get_mod_storage()
local storage_b = core.get_mod_storage()
local function test_mod_storage()
Expand All @@ -86,7 +109,9 @@ end
unittests.register("test_mod_storage", test_mod_storage)

local function test_item_metadata()
test_metadata(ItemStack("unittest:coal_lump"):get_meta())
local meta = ItemStack("unittest:coal_lump"):get_meta()
test_metadata(meta)
test_metadata_compat(meta)
end
unittests.register("test_item_metadata", test_item_metadata)

Expand Down
8 changes: 7 additions & 1 deletion src/script/lua_api/l_metadata.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,13 @@ int MetaDataRef::l_set_string(lua_State *L)

MetaDataRef *ref = checkAnyMetadata(L, 1);
std::string name = luaL_checkstring(L, 2);
auto str = readParam<std::string_view>(L, 3);
std::string_view str;
if (!lua_isnoneornil(L, 3)) {
str = readParam<std::string_view>(L, 3);
} else {
log_deprecated(L, "Value passed to set_string is nil. This behaviour is"
" undocumented and will result in an error in the future.", 1, true);
}

IMetadata *meta = ref->getmeta(!str.empty());
if (meta != NULL && meta->setString(name, str))
Expand Down

0 comments on commit 610c9cd

Please sign in to comment.