简体   繁体   English

如何将对象从c#传递给lua的函数?

[英]How do you pass an object from c# to lua's function?

I'm using Lua interface on c# to pass an object I created to lua's function. 我在c#上使用Lua接口将我创建的对象传递给lua的函数。 It successfully calls the function, but lua is keep throwing an error: 它成功调用了函数,但是lua继续抛出错误:

LuaInterface.LuaException: /hook.lua:32: attempt to index local 'objj' (a nil value) LuaInterface.LuaException:/hook.lua:32:尝试索引本地'objj'(一个零值)

This is the c# code: 这是c#代码:

public class PerObj
{
    public string name;
    public PerObj() 
    {
    }
}

PerObj obj = new PerObj();
LuaFunction lf = lua.GetFunction ("item.HookMe");
lf.Call(obj);

And here's the lua code: 这是lua代码:

function item:HookMe(objj)
    objj.name= "lalala"
end

The function is actually being called, but I'm not sure it's not working... 该函数实际上被调用,但我不确定它是否正常工作...

Change the function definition to: 将函数定义更改为:

function item.HookMe(objj)
    objj.name= "lalala"
end

The colon in the original definition means that the function has also the self parameter. 原始定义中的冒号表示该函数也具有self参数。 Those function are called like this: object:HookMe() . 这些函数被调用如下: object:HookMe() But you want to call it directly, so the colon is not applicable. 但是你想直接调用它,所以冒号不适用。

Edit: 编辑:
If you want to keep the function defininition and retain self , call it like this: 如果你想保持函数定义并保留self ,请像这样调用它:

lf.Call(null, obj);

To call it passing also the self object: 要调用它也传递self对象:

lf.Call(lua["item"], obj);

It seems like the problem is the design of the Lua method (but it really depends on the intent): 似乎问题是Lua方法的设计(但它实际上取决于意图):

Instead of 代替

function item:HookMe(objj)
    -- self not used
    objj.name= "lalala"
end

This would work better in the given example: 在给定的示例中,这将更好地工作:

function item:HookMe()
    self.name= "lalala"
end

The reason (as well discussed in other answers) is that declaring a function with the method syntax ( : ) adds an implied first formal parameter self . 的原因(在其他的答案,以及所讨论的)是声明与方法的语法的函数( : )增加了一个隐含的第一形式参数self The caller can pass anything as the first actual argument but the contract is usually to pass the parent table of the function so it can access its sibling fields. 调用者可以传递任何东西作为第一个实际参数,但合同通常是传递函数的父表,以便它可以访问其兄弟字段。

In this case, name seems to be a sibling of HookMe so the method shouldn't be operating on an arbitrary table passed as objj but instead on self . 在这种情况下, name似乎是HookMe的兄弟,因此该方法不应该在作为objj传递的任意表上运行,而是在self

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM