Skip to content

Instantly share code, notes, and snippets.

@00-matt
Created August 7, 2019 10:18
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 00-matt/8b6cbdc6a5b43431a62d9d9eabf0723e to your computer and use it in GitHub Desktop.
Save 00-matt/8b6cbdc6a5b43431a62d9d9eabf0723e to your computer and use it in GitHub Desktop.
Lua 5.3 Bytecode Example
#include <stdio.h>
#include <stdlib.h>
#include <lua5.3/lua.h>
#include <lua5.3/lualib.h>
#include <lua5.3/lauxlib.h>
static int lua_Writer_file(lua_State *, const void *, size_t, void *);
static void print_usage(FILE *, const char *);
int main(int argc, char **argv) {
lua_State *L;
FILE *outfile;
int status = 0;
if (argc != 3) {
print_usage(stderr, argv[0]);
exit(1);
}
outfile = fopen(argv[2], "wb+");
if (!outfile) {
perror("fopen");
exit(1);
}
L = luaL_newstate();
if (!L) {
perror("luaL_newstate");
fclose(outfile);
exit(1);
}
luaL_openlibs(L);
status = luaL_loadfile(L, argv[1]);
if (status) {
fprintf(stderr, "luaL_loadfile: %s\n", lua_tostring(L, -1));
goto exit;
}
//status = lua_pcall(L, 0, 0, 0);
//if (status) {
// fprintf(stderr, "lua_pcall: %s\n", lua_tostring(L, -1));
// goto exit;
//}
status = lua_dump(L, lua_Writer_file, outfile, 1);
if (status) {
fprintf(stderr, "luaL_loadfile: %s\n", lua_tostring(L, -1));
goto exit;
}
exit:
fclose(outfile);
lua_close(L);
return status;
}
static int lua_Writer_file(lua_State *L, const void *p, size_t sz,
void *ud) {
(void)L;
return fwrite(p, sz, 1, (FILE *)ud) != 1;
}
static void print_usage(FILE *f, const char *p) {
fprintf(f, "Usage: %s <in.lua> <out.bc>\n", p);
}
LDLIBS = -llua5.3
.PHONY: all
all: build run
build: build.c
run: run.c
.PHONY: clean
clean:
rm -f build run
#include <stdio.h>
#include <stdlib.h>
#include <lua5.3/lua.h>
#include <lua5.3/lualib.h>
#include <lua5.3/lauxlib.h>
static void print_usage(FILE *, const char *);
int main(int argc, char **argv) {
lua_State *L;
int status = 0;
if (argc != 2) {
print_usage(stderr, argv[0]);
exit(1);
}
L = luaL_newstate();
if (!L) {
perror("luaL_newstate");
exit(1);
}
luaL_openlibs(L);
// TODO: Use luaL_loadbuffer
status = luaL_loadfile(L, argv[1]);
if (status) {
fprintf(stderr, "luaL_loadfile: %s\n", lua_tostring(L, -1));
goto exit;
}
status = lua_pcall(L, 0, 0, 0);
if (status) {
fprintf(stderr, "lua_pcall: %s\n", lua_tostring(L, -1));
goto exit;
}
exit:
lua_close(L);
return status;
}
static void print_usage(FILE *f, const char *p) {
fprintf(f, "Usage: %s <in.bc>\n", p);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment