lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On 8 Dec 2012, at 18:54, Philipp Kraus wrote:
> 
> Can you send me a working example for 5.2? I try to push a table with function pointer
> to call them in my script. I try to create this:
> 
>       lua_newtable(m_lua);
>       luaL_setfuncs( m_lua, &l_functions[0], 0);
>       lua_pushvalue(m_lua, -1);
>       lua_setglobal(m_lua, p_libname.c_str());
> 
> but in my script I can not call any of my functions (they don't exist). I would like to put
> a set of "global functions" to the script.

I'm a little confused, I thought your earlier posts were about subtables, but in this example it just looks like you're trying to put your functions in one single global table?

This example puts two functions in a table, and then sets the table as a global

#include <lua5.2/lua.hpp>
#include <iostream>

static int hello(lua_State *l) {
	std::cout << "Hello\n" << std::flush;
	return 0;
}

static int goodbye(lua_State *l) {
	std::cout << "Goodbye\n" << std::flush;
	return 0;
}

static luaL_Reg funcs[] = {
	{"hello", hello},
	{"goodbye", goodbye},
	{NULL, NULL}
};

int main() {
	lua_State *l = luaL_newstate();
	
	lua_newtable(l);
	luaL_setfuncs(l, funcs, 0);
	lua_setglobal(l, "greetings");

	luaL_loadstring(l, "greetings.hello() greetings.goodbye()");
	lua_pcall(l, 0, 0, 0);

	lua_close(l);
	return 0;
}

If you're prepared to make the package system available to your scripts, it may be better to use require, luaL_requiref, and luaL_newlib

Thanks,
Kev