Lua userdata not available

我有一些相对简单的Lua代码,它链接到一些C和一些Lua。

local messages = {"Hello World!", "This is some test text", "This is a very long piece of test text with no sense of punctuation or common decency because I want to line wrap okay.", nil}
local i = 1

return  {
    draw = function()
        local blue = zenith.color_rgba(0, 0, 255, 255)
        local white = zenith.color_rgba(255, 255, 255, 255)
        local red = zenith.color_rgba(255, 0, 0, 255)
        local black = zenith.color_rgba(0, 0, 0, 255)

        zenith.clear_to_color(black)

        if(messages[i]) then
            zenith.text_box(white, blue, white, messages[i])
        else
            zenith.text_box(black, red, white, "+++PINEAPPLE ERROR+++\n+++REDO FROM START+++")
        end
    end,

    event = function(ev)
        if(zenith.event_type(ev) == zenith.ev_key_down and
            zenith.event_key_code(ev) == "SPACE" and
            messages[i] -- 不要超出数组范围
        ) then
            i = i+1
        end
    end
}

这个代码的工作方式与我期望的一样。当我按下空格键时,屏幕消息会更改,直到它遇到数组的结尾。'zenith.' 方法都是使用Userdata在C中实现的,用于存储颜色(我有多种构造颜色的方法(rgba、hsl、named)因此将其传递并避免使用数字参数)

然后我尝试更改结构,如下所示:

local messages = {"Hello World!", "This is some test text", "This is a very long piece of test text with no sense of punctuation or common decency because I want to line wrap okay.", nil}
local i = 1

local blue = zenith.color_rgba(0, 0, 255, 255)
local white = zenith.color_rgba(255, 255, 255, 255)
local red = zenith.color_rgba(255, 0, 0, 255)
local black = zenith.color_rgba(0, 0, 0, 255)

return  {
    draw = function()

        zenith.clear_to_color(black)

        if(messages[i]) then
            zenith.text_box(white, blue, white, messages[i])
        else
            zenith.text_box(black, red, white, "+++PINEAPPLE ERROR+++\n+++REDO FROM START+++")
        end
    end,

    event = function(ev)
        if(zenith.event_type(ev) == zenith.ev_key_down and
            zenith.event_key_code(ev) == "SPACE" and
            messages[i] -- 不要超出数组范围
        ) then
            i = i+1
        end
    end
}

唯一的变化是我将颜色(它们是Userdata)提取到了最外层的作用域中。我期望它会继续工作,但不会不断分配/回收颜色。相反,我只得到了黑屏。有什么提示吗?因为它们只在闭包中可用,我的颜色被过早地垃圾收集了吗?还有其他我错过的魔法吗?颜色与“messages”的唯一区别是它们是Userdata。

点赞
用户912318
用户912318

已解决! 在初始化显示之前调用了外部作用域。这会导致颜色创建代码返回一个完全设置为0的颜色对象(因为显然我们不能在显示初始化之前创建颜色,非常有道理(!))。

2018-08-11 01:59:17