Warrick FitzGerald
Warrick FitzGerald

Reputation: 2835

Return a Lua table from C# method without adding it to the global stack

I want to do something like this:

table1 = myFunc("Arg1")  
table2 = myFunc("Arg2")

for key,value in pairs(table1) do print(key,value) end
for key,value in pairs(table2) do print(key,value) end

I'm able to add a table to the global scope of Lua using syntax similar to this:

pLuaVM.NewTable("test");
((LuaTable)pLuaVM["test"])["A"] = 1;
((LuaTable)pLuaVM["test"])["B"] = 2;

and then access that table in Lua doing

for key,value in pairs(test) do print(key,value) end

But I'd rather have my method return the table to a local variable that I can then work with.

Is this possible / am I going in the right direction here?

Upvotes: 2

Views: 1267

Answers (1)

Oliver
Oliver

Reputation: 29591

The following should work (but not tried):

public LuaTable CreateTable()
{
    return (LuaTable)lua.DoString("return {}")[0];
}

public LuaTable YourExportedFunction(string arg)
{
    var table = CreateTable();
    table["A"] = arg;
    table["B"] = 123;
    return table;
}

Then from Lua:

yourTable = YourExportedFunction("arg1")

But if that doesn't work, I don't see how you could avoid globals, although you could hid it via an adapter function:

-- lua: 
function myFunc(arg)
    MyCsFunc(arg)
    local tt = csFuncTable -- bind to table ref'd by csFuncTable
    csFuncTable = nil -- remove from globals
    return tt
end
t1 = myFunc('arg1')
t2 = myFunc('arg2')

// C#: 
public void MyCsFunc(string arg) {
    lua.NewTable("csFuncTable")
    // ... populate table, say
    LuaTable table = lua.GetTable("csFuncTable")
    table[arg1] = 123
}

lua.RegisterFunction(...MyCsFunc...)

You can call myFunc several times because every time, the csFuncTable global gets set to a new table. The global only exists while myFunc is called. Borderline sneaky :)

Upvotes: 1

Related Questions