I am wondering what I am missing in using a custom c function for loadfile in Lua.
#include <stdio.h>
#include <string.h>
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
static void panic(char* error)
{
fprintf(stderr, "panic: %s\n", error);
exit(1);
}
static int _custom_loadfile(lua_State* L)
{
const char* rfile = luaL_checkstring(L, 1);
FILE* rfile_fp = fopen(rfile, "r");
if (rfile_fp == NULL) panic("failed to open rfile.");
if (fseek(rfile_fp, 0, SEEK_END) != 0) panic("failed to seek to eof.");
size_t buffersize = ftell(rfile_fp) + 1 * sizeof(char);
char* buffer = (char*) malloc(buffersize);
if (buffer == NULL) lua_error(L);
if (fseek(rfile_fp, 0, SEEK_SET) != 0) panic("failed to seek to start.");
if (fread(buffer, 1, buffersize, rfile_fp) != buffersize) panic("failed to read file");
int error = luaL_loadbuffer(L, buffer, bufferfilesize, rfile);
if (error) lua_error(...);
return 1; // one value
}
...
int main(int argc, char* argv[])
{
lua_State* L = luaL_newstate();
luaL_openlibs(L);
lua_pushcfunction(L, _custom_loadfile);
lua_setglobal(L, "loadfile");
...
}
example.lua
...
custom_table = loadfile('custom_table')
print(custom_table)
...
custom_table.lua
return {
name = 'custom_table',
other = 'lots of stuff',
table = {},
}
Output
[string "custom_table":165: '<eof>' expected
I have also tried a lua_tostring(L); after the loadbuffer, but that gives me a different error as the data is not a string.