Skip to content

Commit

Permalink
Add code to allow capting all lua run results.
Browse files Browse the repository at this point in the history
  • Loading branch information
daid committed Sep 11, 2024
1 parent 9eea6de commit 5ff9371
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 7 deletions.
20 changes: 20 additions & 0 deletions src/script/conversion.h
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,13 @@

namespace sp::script {

// Special class to capture all results of a run/call as a list of strings.
class CaptureAllResults
{
public:
std::vector<string> result;
};

template<typename T> struct Convert {};
template<> struct Convert<bool> {
static int toLua(lua_State* L, bool value) { lua_pushboolean(L, value); return 1; }
Expand Down Expand Up @@ -60,6 +67,19 @@ template<typename T> struct Convert<std::optional<T>> {
static std::optional<T> fromLua(lua_State* L, int idx) { if (idx <= lua_gettop(L) && !lua_isnil(L, idx)) return Convert<T>::fromLua(L, idx); return {}; }
};

template<> struct Convert<CaptureAllResults> {
static CaptureAllResults fromLua(lua_State* L, int idx) {
CaptureAllResults res;
int nres = lua_gettop(L);
for(int n=2; n<=nres; n++) {
auto s = luaL_tolstring(L, n, nullptr);
lua_pop(L, 1);
res.result.push_back(s);
}
return res;
}
};

template<typename RET, typename... ARGS> struct Convert<RET(*)(ARGS...)> {
using FT = RET(*)(ARGS...);
static int toLua(lua_State* L, FT value) {
Expand Down
18 changes: 11 additions & 7 deletions src/script/environment.h
Original file line number Diff line number Diff line change
Expand Up @@ -82,11 +82,12 @@ class Environment : NonCopyable

private:
template<typename T> Result<T> runImpl(const string& code, const string& name="=[string]") {
int stack_size = lua_gettop(L);
lua_pushcfunction(L, luaErrorHandler);
int result = luaL_loadbufferx(L, code.c_str(), code.length(), name.c_str(), "t");
if (result) {
auto res = Result<T>::makeError(luaL_checkstring(L, -1));
lua_pop(L, 2);
lua_settop(L, stack_size);
return res;
}

Expand All @@ -95,20 +96,23 @@ class Environment : NonCopyable
//set the environment table it as 1st upvalue
lua_setupvalue(L, -2, 1);

result = lua_pcall(L, 0, 1, -2);
if (result)
{
int result_count = 1;
if constexpr (std::is_same_v<T, CaptureAllResults>) {
result_count = LUA_MULTRET;
}
result = lua_pcall(L, 0, result_count, -2);
if (result) {
auto result = Result<T>::makeError(lua_tostring(L, -1));
lua_pop(L, 2);
lua_settop(L, stack_size);
return result;
}

if constexpr (!std::is_void_v<T>) {
auto return_value = Convert<T>::fromLua(L, -1);
lua_pop(L, 2);
lua_settop(L, stack_size);
return return_value;
} else {
lua_pop(L, 2);
lua_settop(L, stack_size);
return {};
}
}
Expand Down

0 comments on commit 5ff9371

Please sign in to comment.