Move load/dump functions to lj_load.c. Add load modes.

This commit is contained in:
Mike Pall
2012-09-21 16:32:24 +02:00
parent 98f05808fa
commit 3dceaa9a74
11 changed files with 197 additions and 139 deletions

View File

@@ -233,83 +233,6 @@ LUALIB_API void luaL_unref(lua_State *L, int t, int ref)
}
}
/* -- Load Lua code ------------------------------------------------------- */
typedef struct FileReaderCtx {
FILE *fp;
char buf[LUAL_BUFFERSIZE];
} FileReaderCtx;
static const char *reader_file(lua_State *L, void *ud, size_t *size)
{
FileReaderCtx *ctx = (FileReaderCtx *)ud;
UNUSED(L);
if (feof(ctx->fp)) return NULL;
*size = fread(ctx->buf, 1, sizeof(ctx->buf), ctx->fp);
return *size > 0 ? ctx->buf : NULL;
}
LUALIB_API int luaL_loadfile(lua_State *L, const char *filename)
{
FileReaderCtx ctx;
int status;
const char *chunkname;
if (filename) {
ctx.fp = fopen(filename, "rb");
if (ctx.fp == NULL) {
lua_pushfstring(L, "cannot open %s: %s", filename, strerror(errno));
return LUA_ERRFILE;
}
chunkname = lua_pushfstring(L, "@%s", filename);
} else {
ctx.fp = stdin;
chunkname = "=stdin";
}
status = lua_load(L, reader_file, &ctx, chunkname);
if (ferror(ctx.fp)) {
L->top -= filename ? 2 : 1;
lua_pushfstring(L, "cannot read %s: %s", chunkname+1, strerror(errno));
if (filename)
fclose(ctx.fp);
return LUA_ERRFILE;
}
if (filename) {
L->top--;
copyTV(L, L->top-1, L->top);
fclose(ctx.fp);
}
return status;
}
typedef struct StringReaderCtx {
const char *str;
size_t size;
} StringReaderCtx;
static const char *reader_string(lua_State *L, void *ud, size_t *size)
{
StringReaderCtx *ctx = (StringReaderCtx *)ud;
UNUSED(L);
if (ctx->size == 0) return NULL;
*size = ctx->size;
ctx->size = 0;
return ctx->str;
}
LUALIB_API int luaL_loadbuffer(lua_State *L, const char *buf, size_t size,
const char *name)
{
StringReaderCtx ctx;
ctx.str = buf;
ctx.size = size;
return lua_load(L, reader_string, &ctx, name);
}
LUALIB_API int luaL_loadstring(lua_State *L, const char *s)
{
return luaL_loadbuffer(L, s, strlen(s), s);
}
/* -- Default allocator and panic function -------------------------------- */
static int panic(lua_State *L)