api - create lua5.2 library from c++ -
i've got experience c lua api, i'm trying create library c++. have following c++ code in main.cpp
:
#include <lua.hpp> #include <iostream> //library function int mylibfunction(lua_state* l){ int argc = lua_gettop(l); for(int i=0; i<argc; i++) { std::cout << " input argument #" << argc-i << ": " << lua_tostring(l, lua_gettop(l)) << std::endl; lua_pop(l, 1); } lua_pushstring(l, "return value"); return 1; } //the library static const struct lual_reg cfunctions[] = { {"mylibfunction", mylibfunction}, {null, null} }; //library open function int luaopen_test (lua_state *l) { lual_newlibtable(l, cfunctions); lual_setfuncs(l, cfunctions, 0); return 1; } int main(int argc, char* argv[]) { lua_state *lua_state; lua_state = lual_newstate(); static const lual_reg lualibs[] = { { "base", luaopen_base }, //load library { "test", luaopen_test }, { null, null} }; const lual_reg *lib = lualibs; for(; lib->func != null; lib++) { lib->func(lua_state); lua_settop(lua_state, 0); } lual_dofile(lua_state, "main.lua"); lua_close(lua_state); }
and in main.lua
file:
mylib = require("test") mylib.mylibfunction(5,2)
the problem library, because if place following code in main.lua file, works charm
print("hello world!")
however, when add simple print statement after library loading, code under here, doesn't run print statement, there must kind of error
print "this shows up" mylib = require("test") mylib.mylibfunction(5,2) print "this doesn't"
am doing wrong in c++, or in lua?
you put function table, never did table. tried call require
, haven't loaded library containing it, nil
. host program doesn't display errors being thrown.
i see tried calling print
. other troubleshooting steps have tried: check require
not nil
. check returns other nil
. check 'mylib.mylibfunction' not nil
. see if calling produces error (e.g. pcall(mylib.mylibfunction,1,2,3)
.
in case, here's working version of code:
#include <lua.hpp> #include <iostream> //library function int mylibfunction(lua_state* l){ int argc = lua_gettop(l); for(int = 1; <= argc; i++) { std::cout << " input argument #" << << ": " << lua_tostring(l, i) << std::endl; } lua_pushstring(l, "return value"); return 1; } //the library static const struct lual_reg cfunctions[] = { {"mylibfunction", mylibfunction}, {null, null} }; //library open function int luaopen_test (lua_state *l) { lual_newlibtable(l, cfunctions); lual_setfuncs(l, cfunctions, 0); return 1; } int main(int argc, char* argv[]) { lua_state *l = lual_newstate(); lual_openlibs(l); lual_requiref(l, "test", luaopen_test, 0); if (lual_dofile(l, "main.lua")) { printf("%s\n", lua_tostring(l, -1)); } lua_close(l); }
note call lual_requiref
. used lual_openlibs
open base libraries. if passed 1
fourth parameter instead of 0
, load test
global environment wouldn't need call require
in script (just standard libraries).
Comments
Post a Comment