从lua将值存储在userdata对象中 [英] Storing values in a userdata object from lua

查看:537
本文介绍了从lua将值存储在userdata对象中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的是这样:

object.foo = "bar"

print(object.foo)

其中对象"是用户数据.

where "object" is a userdata.

我已经使用谷歌搜索了一段时间(使用__newindex和lua_rawset关键字),但是我找不到任何可以满足其要求的示例.

I've been googling for a while (using the keyword __newindex and lua_rawset) but I can't any examples that do what I want it to do.

我想使用C ++中的lua api来实现

I want to do this in with the lua api in c++

推荐答案

让我们用Lua代码编写此代码,以便我们可以使用该代码进行快速实验

Let us write this in Lua code so that we can make quick experiments with the code

function create_object()
  -- ## Create new userdatum with a metatable
  local obj = newproxy(true)
  local store = {}
  getmetatable(obj).__index = store
  getmetatable(obj).__newindex = store
  return obj
end

ud = create_object()
ud.a = 10
print(ud.a)
-- prints '10'

如果使用用户数据,则可能要使用C API进行上述操作.但是,Lua代码应明确指出哪些步骤是必需的. (newproxy(..)函数只是从Lua创建一个虚拟用户数据.)

If you work with userdata you probably want to do the above using the C API. However the Lua code should make it clear extactly which steps are necessary. (The newproxy(..) function simply creates a dummy userdata from Lua.)

这篇关于从lua将值存储在userdata对象中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆