Created
August 8, 2011 05:04
-
-
Save randrews/1131236 to your computer and use it in GitHub Desktop.
Embedding Lua in C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Pack this into an object file with ld: ld -r -b binary -o hello.o hello.lua | |
print "Hello, World!" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <lua.h> | |
#include <lualib.h> | |
#include <lauxlib.h> | |
/* | |
Compile this like so: | |
gcc -o hello_test hello.o main.c -llua | |
*/ | |
extern char binary_hello_lua_start[]; | |
extern char binary_hello_lua_end[]; | |
extern char binary_hello_lua_size[]; | |
int get_module(lua_State *lua); | |
int main(int argc, char **argv){ | |
/* Create and setup the Lua state */ | |
lua_State *lua = lua_open(); | |
luaL_openlibs(lua); | |
/* Add the loader and put it in package.loaders */ | |
lua_register(lua, "get_module", get_module); | |
luaL_dostring(lua, "table.insert(package.loaders, get_module)"); | |
/* Load the module */ | |
luaL_dostring(lua, "require 'hello'"); | |
return 0; | |
} | |
int get_module(lua_State *lua){ | |
const char *modname = luaL_checkstring(lua, 1); | |
/* This is just an example, in a real app we'd | |
turn modname into a real resource pointer | |
instead of just using hello.lua */ | |
if(1 == 1){ | |
luaL_loadbuffer(lua, binary_hello_lua_start, (int)&binary_hello_lua_size, modname); | |
} else { | |
lua_pushnil(lua); | |
} | |
return 1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment