How to pass table arguments from NLUA function to C# method?

509 views Asked by At

I'm using NLUA in a C# project. I use the following code to register a C# method to be availabel in LUA (NLUA) environemnt (and works):

// C# code to register the methoin LUA environment:
Lua state = new Lua();
state["MyLog"] = new LuaLog();

// C# Class and Method:
public class LuaLog {
  public void write(string aLog) {
      LogManager.addLog(aLog);
  }
}

--LUA CODE TO CALL C# METHOD:
MyLog:write("This is a log string")

Well, I want to call "MyLog:write()" but passing a table and not a string. For example:

MyLog:write( {LogText="This is a log string", LogType="INFO"} )

Is it possible? How do I need to write C# method to read that argument as table? I tried:

// C# CODE:
public void write(Dictionary<string, string> aLog)

public void write(List<string> aLog)

But nothing works. Please can you help me?

Thank you!

1

There are 1 answers

0
Alessandro On

Practical example:

public class Example {
    public Dictionary<string, string> MethodCalledFromLua(Object aInput) {
    
      //
      // READ LUA ARGUMENTS WITH THE PROPER TYPE
      //
      if(aInput is LuaTable) {
        LuaTable theLuaTable = aLuaTable as LuaTable;
        Console.WriteLine("LUA TABLE: " + theLuaTable["name"] + " --> " + theLuaTable["surname"]);
      }
    
      if(aInput is string) {
        string theString = aInput as string;
        Console.WriteLine("STRING: " + theString);
      }
    
      //
      // RETURN A DICTIONARY TO LUA (NLUA)
      // (remember that LUA is case-sensitive!)
      //
      Dictionary<string, string> ret = new Dictionary<string, string>();
    
      Dictionary<string, object> editor = FormsManager.newEditor(); 
      ret["DATA_1"] = "My Name";
      ret["DATA_2"] = "My Last Name";
    
      return ret;
        }
      }

REGISTER CLASS IN NLUA from C#:

luaState["MyExample"] = new Example();

LUA CODE:

local ret = MyExample:MethodCalledFromLua( {name = "the name", surname = "the surname" } )
print(ret.DATA_1)