Skip to content

Instantly share code, notes, and snippets.

@btbytes
Forked from randrews/hello.lua
Created August 11, 2011 01:25
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save btbytes/1138712 to your computer and use it in GitHub Desktop.
Embedding Lua in C
-- Pack this into an object file with ld: ld -r -b binary -o hello.o hello.lua
print "Hello, World!"
#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