Question
I want to call the Lua script, which require() lyamlmodule, the Lua binding for LibYAML, from C program.
I compiled Lua 5.2 from the source, and I hacked the module so that it works with Lua 5.2. It can be found on github .
The following is a Lua script, it works either with Lua 5.1, and with 5.2:
-- foo.lua
require('lyaml')
function hello ()
res = lyaml.load("a: 4\n")
return res.a
end
-- then calling hello() it works like a charm
print( hello() ) -> 4
Problem
I wrote a C program that should invoke hello()from a script, following Lua Programming, chapter 25 and the Lua 5.2 Reference Manual .
Program C:
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
int main(void)
{
double z;
lua_State *L = luaL_newstate();
luaL_openlibs(L);
if (luaL_dofile(L, "foo.lua"))
luaL_error(L, "error running script: %s", lua_tostring(L, -1));
lua_getglobal(L, "hello");
if (lua_pcall(L, 0, 1, 0) != 0)
luaL_error(L, "error calling hello: %s", lua_tostring(L, -1));
if (!lua_isnumber(L, -1))
luaL_error(L, "result must be number");
z = lua_tonumber(L, -1);
lua_pop(L, 1);
lua_close(L);
return 0;
}
I am compiling the release:
gcc -Wall -o foo foo.c -ldl -lm -llua
Then when I run fooat runtime, I get the following error:
PANIC: unprotected error in call tu Lua API (
error running script: error loading module 'lyaml' from file '/path/to/lyaml.so':
/path/to/lyaml.so: undefined symbol: lua_gettop)
Aborted
So, I tried to load lyamlfrom program C, adding the following line after the call luaL_openlibs():
luaL_requiref(L, "lyaml", luaopen_package, 1);
:
PANIC: unprotected error in call tu Lua API (
error running script:
hello.lua:4: attempt to index global 'lyaml' (a nil value))
Aborted
, , lyaml , require() .
luaL_requiref(), , modname glb true:
void luaL_requiref (lua_State *L, const char *modname,
lua_CFunction openf, int glb);
openf modname package.loaded[modname], require.
glb , modname.
.
require() Lua script, .
? - ?
, () / :
lua_strlen() -> luaL_len()
luaL_reg -> luaL_Reg
luaL_getn() -> luaL_len()
Lua lyaml , , .
lyaml Lua 5.1. , , .
UPDATE
, , C Lua 5.1. 5.2, .
lyaml = require('lyaml')