public
Last active — forked from randrews/hello.lua

Embedding Lua in C

  • Download Gist
hello.lua
Lua
1 2 3
-- Pack this into an object file with ld: ld -r -b binary -o hello.o hello.lua
 
print "Hello, World!"
main.c
C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
#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;
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.