I'm trying to load the following C library in Lua:
#include <stdio.h>
#include <stdlib.h>
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
void stackDump(lua_State* lua)
{
int i, t;
int top = lua_gettop(lua);
printf("Stack dump: ");
for (i = 1; i <= top; i++)
{
t = lua_type(lua, i);
switch (t)
{
case LUA_TSTRING:
printf("\"%s\"", lua_tostring(lua, i));
break;
case LUA_TBOOLEAN:
printf(lua_toboolean(lua, i) ? "true" : "false");
case LUA_TNUMBER:
printf("%g", lua_tonumber(lua, i));
break;
default:
printf("%s", lua_typename(lua, t));
break;
}
if (i < top)
printf(", ");
}
printf("\n");
}
int myPrint(lua_State* lua)
{
stackDump(lua);
const char* str = luaL_checkstring(lua, 1);
printf("myPrint: %s\n", str);
lua_newtable(lua);
lua_pushinteger(lua, 1);
lua_pushstring(lua, "myPrint");
lua_settable(lua, -3);
lua_pushinteger(lua, 2);
lua_pushstring(lua, str);
lua_settable(lua, -3);
return 2;
}
static const struct luaL_Reg myScrewedLib[] = {
{"myPrint", myPrint},
{NULL, NULL}
};
int luaopen_myScrewedLib(lua_State* lua)
{
luaL_newlib(lua, myScrewedLib);
printf("SCREW IT\n");
return 1;
}
I'm compiling this file with:
gcc -Wall -fpic -llua -shared -o myScrewedLib.so tut1.c
I see the following when running in the interpreter:
$ lua
Lua 5.2.2 Copyright (C) 1994-2013 Lua.org, PUC-Rio
> local m = require("myScrewedLib")
SCREW IT
> for k, v in pairs(m) do print(k, v) end
stdin:1: bad argument #1 to 'pairs' (table expected, got nil)
stack traceback:
[C]: in function 'pairs'
stdin:1: in main chunk
[C]: in ?
>
I wouldn't expect m
to be nil
here. The book mentions the use of lua_pushcfunction()
but only when it's a "quick-and-dirty way"[1] to run the function from the interpreter. Other examples of using the methods in this C file dont use lua_pushcfunction()
as they imply that the luaL_Reg
struct is how Lua knows what can be called[2].
[1] Programming in Lua 3rd Edition, p.274
[2] Programming in Lua 3rd Edition, p.279