Skip to content

Instantly share code, notes, and snippets.

@thales17
Last active June 9, 2020 15:43
Show Gist options
  • Save thales17/2a81ceae465ca6eb094fa368532c03e2 to your computer and use it in GitHub Desktop.
Save thales17/2a81ceae465ca6eb094fa368532c03e2 to your computer and use it in GitHub Desktop.
Embedding Lua Scripts into C programs

Embedding Lua into C Programs

  • This code was run on macOS with lua version 5.3.5 install via brew brew install lua
  • The shows an example calling lua from C and calling C from lua

Expected output:

This line in directly from C

lua init
lua update: 0.0
lua draw
lua update: 0.33333333333333
lua draw
lua update: 0.66666666666667
lua draw
lua update: 1.0
lua draw
lua update: 1.3333333333333
lua draw
lua update: 1.6666666666667
lua draw
lua update: 2.0
lua draw
lua update: 2.3333333333333
lua draw
lua update: 2.6666666666667
lua draw
lua update: 3.0
lua draw
lua update: 3.3333333333333
lua draw
lua update: 3.6666666666667
lua draw
lua update: 4.0
lua draw
lua update: 4.3333333333333
lua draw
lua update: 4.6666666666667
lua draw
lua update: 5.0
lua draw
lua update: 5.3333333333333
lua draw
lua update: 5.6666666666667
lua draw
lua update: 6.0
lua draw

Back to C again
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
int count = 0;
void error (lua_State *L, const char *fmt, ...) {
va_list argp;
va_start(argp, fmt);
vfprintf(stderr, fmt, argp);
va_end(argp);
lua_close(L);
exit(EXIT_FAILURE);
}
void l_call(lua_State *L, const char *f) {
lua_getglobal(L, f);
if (lua_pcall(L, 0, 1, 0) != LUA_OK) {
error(L, "error running function 'init': %s", lua_tostring(L, -1));
}
}
static int l_get_count(lua_State *L) {
lua_pushnumber(L, count);
count++;
return 1;
}
int main (void) {
char buff[256];
int error;
lua_State *L =luaL_newstate();
luaL_openlibs(L);
lua_pushcfunction(L, l_get_count);
lua_setglobal(L, "count");
printf("This line in directly from C\n\n");
error = luaL_loadfile(L, "script.lua") || lua_pcall(L, 0, 0, 0);
if (error) {
fprintf(stderr, "%s", lua_tostring(L, -1));
lua_pop(L, 1); /* pop error message from the stack */
}
l_call(L, "init");
int i;
while (i < 20) {
l_call(L, "update");
l_call(L, "draw");
i++;
}
printf("\nBack to C again\n\n");
lua_close(L);
return 0;
}
build:
cc -o embed Embed_lua.c -I/usr/local/include/lua -llua
function init()
print("lua init")
end
function update()
local c = count()
c = c/3
print("lua update: "..c)
end
function draw()
print("lua draw")
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment