Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include "lua5.1/lua.hpp"
- class Computer {
- public:
- Computer();
- ~Computer();
- void run();
- void test(int i);
- private:
- lua_State *luaState;
- };
- Computer * get_obj_pointer(lua_State *L)
- {
- lua_getglobal(L, "computer");
- if (!lua_istable(L, -1))
- luaL_error(L, "Table 'computer' is not found!");
- lua_pushstring(L, "_self");
- lua_gettable(L, -2);
- if (!lua_isuserdata(L, -1))
- luaL_error(L, "Value 'computer._self' is not found!");
- void *p = lua_touserdata(L, -1);
- lua_pop(L, 1);
- return (Computer *) p;
- }
- int test_wrap(lua_State *L)
- {
- // read arguments
- if(!lua_isnumber(L, -1))
- luaL_error(L, "Expected a Number as a first argument!");
- int i = lua_tonumber(L, -1);
- // restore pointer to object
- Computer * pComp = get_obj_pointer(L);
- // call object method
- if (pComp) {
- pComp->test(i);
- }
- return 0;
- }
- Computer::Computer(void) {
- luaState = luaL_newstate();
- luaL_openlibs( luaState );
- lua_createtable(luaState, 0, 2);
- lua_pushlightuserdata(luaState, this);
- lua_setfield(luaState, -2, "_self");
- lua_pushcfunction(luaState, test_wrap);
- lua_setfield(luaState, -2, "test");
- lua_setglobal(luaState, "computer");
- }
- Computer::~Computer(void) {
- lua_close(luaState);
- }
- void Computer::run(void) {
- int err = luaL_dofile(luaState, "script.lua");
- if (err) {
- std::cout << "Error: " << lua_tostring(luaState, -1);
- lua_pop(luaState, 1);
- }
- }
- void Computer::test(int i) {
- std::cout << "test: " << i;
- }
- int main()
- {
- Computer c;
- c.run();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement