about summary refs log tree commit diff stats
path: root/src/lua.c
diff options
context:
space:
mode:
authorKartik K. Agaram <vc@akkartik.com>2021-11-05 08:54:19 -0700
committerKartik K. Agaram <vc@akkartik.com>2021-11-05 08:54:19 -0700
commitb4d86665b8bb42de74ffc52e123b7383e3128f9f (patch)
tree93ab95de8ff72dc96d7d1dac69c1900239b3bfd4 /src/lua.c
parentf53ca6f804a8a11597206fdc2f8976b10a2b936a (diff)
downloadteliva-b4d86665b8bb42de74ffc52e123b7383e3128f9f.tar.gz
https://www.lua.org/pil/28.2.html
Diffstat (limited to 'src/lua.c')
-rw-r--r--src/lua.c23
1 files changed, 16 insertions, 7 deletions
diff --git a/src/lua.c b/src/lua.c
index 3182546..2ee46d6 100644
--- a/src/lua.c
+++ b/src/lua.c
@@ -386,18 +386,28 @@ static int newarray (lua_State *L) {
   int n = luaL_checkint(L, 1);
   size_t nbytes = sizeof(NumArray) + n*sizeof(double);
   NumArray *a = (NumArray *)lua_newuserdata(L, nbytes);
+
+  luaL_getmetatable(L, "meta.array");
+  lua_setmetatable(L, -2);
+
   a->size = n;
   return 1;  /* new userdatum is already on the stack */
 }
 
 
+/* ensure bottom of stack is an array */
+static NumArray *checkarray (lua_State *L) {
+  void *ud = luaL_checkudata(L, 1, "meta.array");
+  luaL_argcheck(L, ud != NULL, 1, "`array' expected");
+  return (NumArray *)ud;
+}
+
+
 static int setarray (lua_State *L) {
-  NumArray *a = (NumArray *)lua_touserdata(L, 1);
+  NumArray *a = checkarray(L);
   int index = luaL_checkint(L, 2);
   double value = luaL_checknumber(L, 3);
 
-  luaL_argcheck(L, a != NULL, 1, "`array' expected");
-
   luaL_argcheck(L, 1 <= index && index <= a->size, 2,
                    "index out of range");
 
@@ -407,11 +417,9 @@ static int setarray (lua_State *L) {
 
 
 static int getarray (lua_State *L) {
-  NumArray *a = (NumArray *)lua_touserdata(L, 1);
+  NumArray *a = checkarray(L);
   int index = luaL_checkint(L, 2);
 
-  luaL_argcheck(L, a != NULL, 1, "`array' expected");
-
   luaL_argcheck(L, 1 <= index && index <= a->size, 2,
                    "index out of range");
 
@@ -421,7 +429,7 @@ static int getarray (lua_State *L) {
 
 
 static int getsize (lua_State *L) {
-  NumArray *a = (NumArray *)lua_touserdata(L, 1);
+  NumArray *a = checkarray(L);
   luaL_argcheck(L, a != NULL, 1, "`array' expected");
   lua_pushnumber(L, a->size);
   return 1;
@@ -445,6 +453,7 @@ int main (int argc, char **argv) {
     l_message(argv[0], "cannot create state: not enough memory");
     return EXIT_FAILURE;
   }
+  luaL_newmetatable(L, "meta.array");
   luaL_register(L, "array", arraylib);
 //?   luaL_register(L, "curses.window", curses_window_fns);
   initscr();