-
-
Save hltbra/81f8aac9603b5f3901205d90c7eed203 to your computer and use it in GitHub Desktop.
Demo of Lua integrated with C
This file contains 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 <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; | |
} |
This file contains 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
$ 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