从C api访问userdata中的Lua变量(Access Lua variables in userdata from the C api)

编程入门 行业动态 更新时间:2024-10-26 11:22:08
从C api访问userdata中的Lua变量(Access Lua variables in userdata from the C api)

我正在研究一个用C ++编写的项目,该项目使用Lua作为脚本语言。 为了便于调试,我们实现了一个网络调试器,它接收Lua代码,运行它,对Json中的返回值进行编码并将该字符串发回。

我设法为表实现了这个,但现在我被困在存储在userdata中的变量。 我有这个Lua代码:

Elements.Avatar.testVar = 5 Elements.testVar = 15 return Elements // result { "result0": "{Application:userdata; Avatar:userdata; Physics:userdata; testVar:15; }" }

Application , Avatar和Physics是使用C ++创建的对象。 然而,这两个testVars已在上面的脚本中创建。 Elements是一个表,所以我可以列出所有元素,但Avatar.testVar似乎是隐藏的,因为Avatar是一个LUA_TUSERDATA 。

有没有人知道如何检测已添加到Lua中的userdata的变量?

I am working on a project written in C++ which uses Lua as a scripting language. In order to facilitate debugging we implemented a network debugger which receives Lua code, runs it, encodes the return values in Json and sends that string back.

I managed to implement that for tables, but now I am stuck with variables stored in userdata. E.g. I have this Lua code:

Elements.Avatar.testVar = 5 Elements.testVar = 15 return Elements // result { "result0": "{Application:userdata; Avatar:userdata; Physics:userdata; testVar:15; }" }

Application, Avatar and Physics are objects that have been created in C++. The two testVars however have been created in the script above. Elements is a table, so I can list all elements, but Avatar.testVar seems to be hidden because Avatar is a LUA_TUSERDATA.

Does anyone have an idea how I can detect variables that have been added to userdata in Lua?

最满意答案

没有“存储在userdata中的变量”这样的东西,至少,就Lua而言,并非如此。 从Lua的角度来看,userdata是一个巨大的黑盒子。 所有Avatar.testVar = 5都会使用字符串testVar和新值15调用Avatar的metamethod __newindex 。 你的C ++元方法(因为只有C ++代码可以将元方法放在userdata上)解释这完全取决于你的代码。

所以Lua无法做到这一点。 您的代码需要提供调试挂钩。 Lua 5.2允许您实现__pairs和__ipairs元方法,其中pairs和ipairs函数可以用来迭代您的值。 除此之外,您可以自己查询用户数据中存在和不存在的内容。

There is no such thing as a "variable stored in userdata", At least, not as far as Lua is concerned. From Lua's perspective, userdata is a giant black box. All Avatar.testVar = 5 does is call the metamethod __newindex in Avatar with the string testVar and the new value 15. How your C++ metamethod (because only C++ code can put metamethods on userdata) interprets this is entirely up to your code.

So it can't be done from Lua. Your code will need to provide debugging hooks. Lua 5.2 allows you to implement the __pairs and __ipairs metamethods, which the pairs and ipairs functions can use to iterate over your values. Outside of that, you're on your own for querying what does and doesn't exist in a userdata.

更多推荐

本文发布于:2023-07-19 01:07:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1169727.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   userdata   api   Lua   variables

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!