Skip to content

Instantly share code, notes, and snippets.

@hltbra
Created April 6, 2020 17:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hltbra/81f8aac9603b5f3901205d90c7eed203 to your computer and use it in GitHub Desktop.
Save hltbra/81f8aac9603b5f3901205d90c7eed203 to your computer and use it in GitHub Desktop.
Demo of Lua integrated with C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
int main (int argc, char *argv[]) {
if (argc < 3) {
fprintf(stderr, "Missing arguments. Use it like ./program <a> <b>\n");
return 1;
}
lua_State *L = luaL_newstate();
char *code = \
"function add(a, b)\n" \
"return a + b\n" \
"end\n";
/* interpret lua code stored in `code` */
luaL_loadbuffer(L, code, strlen(code), "inline");
lua_pcall(L, 0, 0, 0);
/* call the function `add` defined by the previous snippet */
lua_getglobal(L, "add");
lua_pushnumber(L, atof(argv[1]));
lua_pushnumber(L, atof(argv[2]));
lua_pcall(L, 2, 1, 0);
/* the result of the previous function is at the top of the stack (-1) */
printf("Result: %lf\n", lua_tonumber(L, -1));
lua_close(L);
return 0;
}
$ gcc -Ilua-5.3.5/src/ lua-5.3.5/src/liblua.a -lm b.c -o add.out
$ ./add.out 12.4 1.3
Result: 13.700000
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment