Cleaned up argument parsing.
This commit is contained in:
parent
4188c2164d
commit
1b43ee552b
33
limmutable.c
33
limmutable.c
@ -416,17 +416,15 @@ static const luaL_Reg R[] =
|
||||
|
||||
static int Lmake_class(lua_State *L)
|
||||
{
|
||||
// args: fields, [methods/metamethods]
|
||||
int n_args = lua_gettop(L);
|
||||
|
||||
// CLS = {}
|
||||
// immutable([fields], [methods/metamethods])
|
||||
|
||||
lua_newtable(L);
|
||||
// Stack: [CLS]
|
||||
// Populate CLS.__len, CLS.__index, CLS.__pairs, etc.
|
||||
luaL_register(L,NULL,R);
|
||||
|
||||
// If methods were passed in, copy them over, overwriting defaults if desired
|
||||
if (n_args >= 2) {
|
||||
if (lua_type(L, 2) == LUA_TTABLE) {
|
||||
// Stack: [CLS]
|
||||
lua_pushnil(L);
|
||||
// Stack: [CLS, nil]
|
||||
@ -457,16 +455,21 @@ static int Lmake_class(lua_State *L)
|
||||
lua_setfield(L, -2, "__fields");
|
||||
// Stack: [CLS]
|
||||
|
||||
size_t n = lua_objlen(L, 1);
|
||||
lua_createtable(L, 0, n);
|
||||
// Stack: [CLS, __indices]
|
||||
lua_pushnil(L);
|
||||
while (lua_next(L, 1) != 0) {
|
||||
// Stack: [CLS, __indices, i, fieldname]
|
||||
lua_pushvalue(L, -2);
|
||||
// Stack: [CLS, __indices, i, fieldname, i]
|
||||
lua_settable(L, -4);
|
||||
// Stack: [CLS, __indices, i]
|
||||
if (lua_type(L, 1) != LUA_TTABLE) {
|
||||
// If no fields were passed in, make them empty (i.e. a singleton)
|
||||
lua_createtable(L, 0, 0);
|
||||
} else {
|
||||
size_t n = lua_objlen(L, 1);
|
||||
lua_createtable(L, 0, n);
|
||||
// Stack: [CLS, __indices]
|
||||
lua_pushnil(L);
|
||||
while (lua_next(L, 1) != 0) {
|
||||
// Stack: [CLS, __indices, i, fieldname]
|
||||
lua_pushvalue(L, -2);
|
||||
// Stack: [CLS, __indices, i, fieldname, i]
|
||||
lua_settable(L, -4);
|
||||
// Stack: [CLS, __indices, i]
|
||||
}
|
||||
}
|
||||
lua_setfield(L, -2, "__indices");
|
||||
// Stack: [CLS]
|
||||
|
9
test.lua
9
test.lua
@ -78,7 +78,7 @@ test("Testing from_table", function()
|
||||
assert(Vec:from_table({x=1}) == Vec(1, nil))
|
||||
end)
|
||||
|
||||
test("Testing singletons", function()
|
||||
test("Testing equality", function()
|
||||
also_v = Vec(1,3)
|
||||
assert(v == also_v)
|
||||
assert(tostring(v) == tostring(also_v))
|
||||
@ -90,6 +90,13 @@ test("Testing singletons", function()
|
||||
assert(not_v == also_not_v)
|
||||
end)
|
||||
|
||||
test("Testing singletons", function()
|
||||
local T1 = immutable()
|
||||
local T2 = immutable()
|
||||
assert(T1() == T1())
|
||||
assert(T1() ~= T2())
|
||||
end)
|
||||
|
||||
test("Testing __add metamethod", function()
|
||||
assert(v + Vec(5,6) == Vec(6,9))
|
||||
end)
|
||||
|
Loading…
Reference in New Issue
Block a user