fengari-lua / fengari

🌙 φεγγάρι - The Lua VM written in JS ES6 for Node and the browser

Home Page:https://fengari.io/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How do I use lua_dump?

grilme99 opened this issue · comments

I need to convert Lua code into bytecode. I've seen that you should use lua_dump but I have no idea how to do that in JavaScript. Any help?

You'd do it the same way as in C: with the function on the stack, call lua_dump with a relevant writer function. You can use string.dump as a guide:

fengari/src/lstrlib.js

Lines 146 to 155 in 0c9631c

const str_dump = function(L) {
let b = new luaL_Buffer();
let strip = lua_toboolean(L, 2);
luaL_checktype(L, 1, LUA_TFUNCTION);
lua_settop(L, 1);
luaL_buffinit(L, b);
if (lua_dump(L, writer, b, strip) !== 0)
return luaL_error(L, to_luastring("unable to dump given function"));
luaL_pushresult(b);
return 1;

But how do I use and make a writer function? That's the bit I didn't understand, sorry for not clarifying that.

But how do I use and make a writer function?

See just above the code I linked:

const writer = function(L, b, size, B) {
    luaL_addlstring(B, b, size);
    return 0;
};

From the lua manual:

lua_dump calls the writer, passing along the buffer to be written (p), its size (sz), and the data parameter supplied to lua_dump.

The writer returns an error code: 0 means no errors; any other value means an error and stops lua_dump from calling the writer again.