Created
March 30, 2024 11:45
-
-
Save denisdemaisbr/7d03c32000b3b273ade7621d559599a3 to your computer and use it in GitHub Desktop.
It's show how create a minimal lua interpreter with some features
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
/* | |
denis dos santos silva | |
2024-03-30 | |
*/ | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <stdbool.h> | |
#include <string.h> | |
#include <time.h> | |
#include <ctype.h> | |
#include <errno.h> | |
#include <assert.h> | |
#include "lua.h" | |
#include "lualib.h" | |
#include "lauxlib.h" | |
int main( const int argc, const char *argv[] ) { | |
lua_State *L; | |
int exit_code = 0; | |
srand(time(NULL)); | |
// disable output buffering | |
setbuf(stdout, NULL); | |
// luavm | |
L = luaL_newstate(); | |
if (!L) | |
exit(1); | |
luaL_openlibs(L); | |
// register 'argv' | |
{ | |
lua_newtable(L); | |
for (int i=0; i<argc; i++) { | |
lua_pushinteger(L, i+1); | |
lua_pushstring(L, argv[i]); | |
lua_settable(L, -3); | |
} | |
lua_setglobal(L, "argv"); | |
lua_settop(L, 0); | |
} | |
// run script | |
if (luaL_dofile(L, "main.lua") != 0) { | |
fprintf(stderr,"[error] %s\n",lua_tostring(L,-1)); | |
lua_settop(L, 0); | |
exit_code = 1; | |
} | |
lua_close(L); | |
return exit_code; | |
} | |
/* | |
main.lua: | |
print( _VERSION ) | |
print('argv', type(argv)) | |
print("dump table"); | |
print(table.concat(argv, '\n')) | |
output: | |
$ ./test 12 3 4 | |
Lua 5.4 | |
argv table | |
dump table | |
X:\test.exe | |
12 | |
3 | |
4 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment