简体   繁体   English

使用从C ++对象到另一个C ++对象的指针,从Lua修改成员变量

[英]using a pointer from a C++ object, to another C++ object, to modify member variables, from Lua

How do you get a reference to a C++ object, from another C++ object, inside a Lua script? 如何在Lua脚本中从另一个C ++对象获得对C ++对象的引用? I don't really know how to summarize that in words properly, so let me elaborate with a Lua example first: 我真的不知道如何正确地用语言概括,所以让我先用Lua的例子详细说明:

function doSomething()
    compo = a:getComponent()
    compo:setVariable(0)
end

a is a C++ object, and the function getComponent returns a pointer: a是一个C ++对象,函数getComponent返回一个指针:

// inside A.h
Component* A::getComponent();

It seems the problem is that getComponent() is passing a copy of the Component object to Lua, instead of a reference. 似乎问题是getComponent()将Component对象的副本传递给Lua而不是引用。 I come across the same problem with every function that returns a pointer, Lua cannot modify the original object. 我遇到了与返回指针的每个函数相同的问题,Lua无法修改原始对象。

Object a seems to be working correctly, if I modify a variable from within Lua, it's outcome is mirrored in C++. 对象a似乎工作正常,如果我从Lua中修改变量,它的结果在C ++中被镜像。 Both A and component are bound to Lua already, as well as the required methods. A和组件都已经绑定到Lua,以及所需的方法。

Am I missing something syntactically or is there more to it than that? 我是否在语法上遗漏了什么或者还有更多的东西呢?

I am using luabind, Lua 5.1, and MinGW. 我正在使用luabind,Lua 5.1和MinGW。 Thanks for any help in advance. 在此先感谢您的帮助。

EDIT 编辑

Here is the luabind code. 这是luabind代码。 I summarized it because there's a bunch of other binds that have no relation to the problem: 我总结了它,因为有一堆与问题无关的其他绑定:

luabind::class_<A>("A")
    .def("getComponent", &A::getComponent)

Make a Lua wrapper for the "component" too. 为“组件”制作一个Lua包装器。 Then make a:getComponent() return the Lua object, not a real reference for the C++ object. 然后创建a:getComponent()返回Lua对象,而不是C ++对象的真实引用。 Add any methods you need on that new wrapper object. 在新的包装器对象上添加所需的任何方法。 If you have more "objects", rinse and repeat. 如果您有更多“物体”,请冲洗并重复。

In short: for every object you want to manipulate from Lua, you will have to create a Lua wrapper. 简而言之:对于你想要从Lua操作的每个对象,你必须创建一个Lua包装器。 The only way around that is creating extra functions on the top level object, and calling those from Lua ( a:setComponentVariable(0) instead of a:getComponent() + compo:setVariable(0) ). 唯一的方法是在顶级对象上创建额外的函数,并从Lua调用那些函数( a:setComponentVariable(0)而不是a:getComponent() + compo:setVariable(0) )。

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

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