Skip to content

Commit

Permalink
Change cat.decode from taking a bool to an int (true -> cat.expanded)…
Browse files Browse the repository at this point in the history
… and add withorder flag
  • Loading branch information
Sainan committed Feb 28, 2024
1 parent 8568d92 commit 7af605d
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 6 deletions.
37 changes: 32 additions & 5 deletions src/lcatlib.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ static int cat_encode (lua_State *L) {
return 1;
}

static void cat_decode_aux (lua_State *L, const soup::catNode& node) {
static void cat_decode_aux (lua_State *L, const soup::catNode& node, bool withorder) {
if (!node.value.empty()) {
lua_pushliteral(L, "__value");
pluto_pushstring(L, node.value);
Expand All @@ -54,13 +54,24 @@ static void cat_decode_aux (lua_State *L, const soup::catNode& node) {
pluto_pushstring(L, child->name);
if (!child->children.empty()) {
lua_newtable(L);
cat_decode_aux(L, *child);
cat_decode_aux(L, *child, withorder);
}
else {
pluto_pushstring(L, child->value);
}
lua_settable(L, -3);
}
if (withorder) {
lua_pushliteral(L, "__order");
lua_newtable(L);
lua_Integer i = 1;
for (const auto& child : node.children) {
lua_pushinteger(L, i++);
pluto_pushstring(L, child->name);
lua_settable(L, -3);
}
lua_settable(L, -3);
}
}

static void cat_decode_aux_expanded (lua_State* L, const soup::catNode& node) {
Expand Down Expand Up @@ -91,15 +102,19 @@ static void cat_decode_aux_expanded (lua_State* L, const soup::catNode& node) {
}

static int cat_decode (lua_State *L) {
int flags = (int)luaL_optinteger(L, 2, 0);
const bool expanded = (flags & (1 << 0));
const bool withorder = (flags & (1 << 1));
if (expanded && withorder)
luaL_error(L, "cat.expanded and cat.withorder are mutually exclusive");
std::string data = pluto_checkstring(L, 1);
const bool expanded = lua_istrue(L, 2);
soup::StringRefReader sr(data);
if (auto root = soup::catParse(sr)) {
lua_newtable(L);
if (expanded)
cat_decode_aux_expanded(L, *root);
else
cat_decode_aux(L, *root);
cat_decode_aux(L, *root, withorder);
return 1;
}
return 0;
Expand All @@ -111,4 +126,16 @@ static const luaL_Reg funcs[] = {
{nullptr, nullptr}
};

PLUTO_NEWLIB(cat)
LUAMOD_API int luaopen_cat (lua_State *L) {
luaL_newlib(L, funcs);

// decode flags
lua_pushinteger(L, 1 << 0);
lua_setfield(L, -2, "expanded");
lua_pushinteger(L, 1 << 1);
lua_setfield(L, -2, "withorder");

return 1;
}

const Pluto::PreloadedLibrary Pluto::preloaded_cat{ "cat", funcs, &luaopen_cat };
2 changes: 1 addition & 1 deletion testes/pluto/basic.pluto
Original file line number Diff line number Diff line change
Expand Up @@ -1614,7 +1614,7 @@ do
assert(cat.encode(t) == data)

data = "First\nSecond"
t = cat.decode(data, true)
t = cat.decode(data, cat.expanded)
assert(t[1].name == "First")
assert(t[2].name == "Second")
end
Expand Down

0 comments on commit 7af605d

Please sign in to comment.