Added from_table()

This commit is contained in:
Bruce Hill 2018-02-09 18:21:49 -08:00
parent bf95f0e317
commit 7cb9ccc223
2 changed files with 37 additions and 1 deletions

View File

@ -36,7 +36,11 @@ static int Lcreate_instance(lua_State *L)
// Stack: [__fields]
size_t n = lua_objlen(L,-1);
if ((size_t)n_args-1 != n) {
lua_pushstring(L, "incorrect number of arguments");
lua_pushstring(L, "incorrect number of arguments: expected ");
lua_pushinteger(L, n);
lua_pushstring(L, ", but got ");
lua_pushinteger(L, n_args-1);
lua_concat(L, 4);
lua_error(L);
}
lua_pop(L,1);
@ -170,6 +174,32 @@ static int Lcreate_instance(lua_State *L)
return 1;
}
static int Lfrom_table(lua_State *L)
{
lua_pushvalue(L, 1);
// Stack: [mt]
lua_getfield(L, -1, "__fields");
// Stack: [mt, fields]
lua_pushnil(L);
int num_args = 0;
while (lua_next(L, -2) != 0) {
// Stack: [mt, fields, i, field_i]
lua_gettable(L, 2);
// Stack: [mt, fields, i, table[field_i]]
lua_insert(L, -3);
// Stack: [mt, table[field_i], fields, i]
num_args++;
}
// Stack: [mt, table[field], ..., fields]
lua_pop(L, 1);
// Stack: [mt, table[field], ...]
lua_pushcfunction(L, Lcreate_instance);
// Stack: [mt, table[field], ..., create]
lua_insert(L, -(num_args+2));
// Stack: [create, mt, table[field_1], ...]
lua_call(L, num_args+1, 1);
return 1;
}
static int Llen(lua_State *L)
{
@ -351,6 +381,7 @@ static const luaL_Reg R[] =
{ "__index", Lindex},
{ "__ipairs", Lipairs},
{ "__pairs", Lpairs},
{ "from_table", Lfrom_table},
{ NULL, NULL}
};

View File

@ -73,6 +73,11 @@ end)
test("Testing tostring", function()
assert(tostring(v) == "Vec(1, 3)")
end)
test("Testing from_table", function()
assert(Vec:from_table({y=3,x=1}) == v)
end)
test("Testing singletons", function()
also_v = Vec(1,3)
assert(v == also_v)