Add lua_rawsetfield (#671)

Luau currently has the following functions in the C API for dealing with
tables without invoking metamethods:

lua_rawgetfield
lua_rawget
lua_rawgeti
lua_rawset
lua_rawseti

This change adds the missing function lua_rawsetfield for consistency
and because it's more efficient to use it in place of plain lua_rawset
which requires pushing the key and value separately.

Co-authored-by: Petri Häkkinen <petrih@rmd.remedy.fi>
This commit is contained in:
Petri Häkkinen 2022-09-15 18:26:54 +03:00 committed by GitHub
parent 366df96393
commit 6fbea7cc84
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 18 additions and 2 deletions

View file

@ -210,6 +210,7 @@ LUA_API void lua_getfenv(lua_State* L, int idx);
*/
LUA_API void lua_settable(lua_State* L, int idx);
LUA_API void lua_setfield(lua_State* L, int idx, const char* k);
LUA_API void lua_rawsetfield(lua_State* L, int idx, const char* k);
LUA_API void lua_rawset(lua_State* L, int idx);
LUA_API void lua_rawseti(lua_State* L, int idx, int n);
LUA_API int lua_setmetatable(lua_State* L, int objindex);

View file

@ -847,6 +847,19 @@ void lua_setfield(lua_State* L, int idx, const char* k)
return;
}
void lua_rawsetfield(lua_State* L, int idx, const char* k)
{
api_checknelems(L, 1);
StkId t = index2addr(L, idx);
api_check(L, ttistable(t));
if (hvalue(t)->readonly)
luaG_runerror(L, "Attempt to modify a readonly table");
setobj2t(L, luaH_setstr(L, hvalue(t), luaS_new(L, k)), L->top - 1);
luaC_barriert(L, hvalue(t), L->top - 1);
L->top--;
return;
}
void lua_rawset(lua_State* L, int idx)
{
api_checknelems(L, 2);

View file

@ -746,6 +746,8 @@ TEST_CASE("ApiTables")
lua_newtable(L);
lua_pushnumber(L, 123.0);
lua_setfield(L, -2, "key");
lua_pushnumber(L, 456.0);
lua_rawsetfield(L, -2, "key2");
lua_pushstring(L, "test");
lua_rawseti(L, -2, 5);
@ -761,8 +763,8 @@ TEST_CASE("ApiTables")
lua_pop(L, 1);
// lua_rawgetfield
CHECK(lua_rawgetfield(L, -1, "key") == LUA_TNUMBER);
CHECK(lua_tonumber(L, -1) == 123.0);
CHECK(lua_rawgetfield(L, -1, "key2") == LUA_TNUMBER);
CHECK(lua_tonumber(L, -1) == 456.0);
lua_pop(L, 1);
// lua_rawget