【问题标题】:Lua: How to assigned a return value from a function to a local value of a different function in luaLua:如何将函数的返回值分配给lua中不同函数的局部值
【发布时间】:2019-06-12 03:58:44
【问题描述】:

我正在编写一个极其简单的 lua 脚本,用于计算 LED 闪光灯的次数

但是,当我尝试将前一个函数的返回值分配给另一个函数中的局部变量时,它一直给我错误。

function ReadADC1()
    local adc_voltage_value = 0
    adc_voltage_value = tonumber(adc.readadc()) * 2 -- 0.10 --get dec number out of this -- need to know where package adc come from
    --convert to voltage
    adc_voltage_value = adc_voltage_value *0.000537109375 --get V
    adc_voltage_value = math.floor(adc_voltage_value *1000 +0.5) --since number is base off resolution

    --print (adc_voltage_value)
    return adc_voltage_value

end
-- end of readADC1() TESTED

function counter()

    local ledValue = readADC1()
    --local interval -- interval between led on and off. If interval larger than 1 second, reset counter 

    --TODO add interval definition

    local interval = os.clock()
    while (true) do
        if ((ledValue >= OnThreshHold) and (interval < 1000)) then -- if value exceed threshhold, mean it on 
                ledCounter = ledCounter + 1
        elseif ((ledValue < OnThreshHold) and (os.clock() - interval > 1000)) then -- if led off for longer than 1 second
                ledCounter = 0  -- reset counter to one and prepare for next flashing
        else
            ledCounter = ledCounter -- not sure if we need this. Doing this might cause bug later on
        end
    end
    --return ledCounter
    print (ledCounter,"\r\n")
    end
-- end of counter()

如您所见,我正在尝试使用 ReadADC1 函数中的 adc_voltage_value 分配 ledValue。我以为它应该工作,但结果它没有。它给了我这个错误:

> +LUA ERROR: LEDcounter.lua:29: attempt to call global 'readADC1' (a nil value)
> 
> stack traceback:
> 
>     LEDcounter.lua:29: in main chunk
> 
>     [C]: ?

我使用黑盒调试并独立测试每个功能,ReadADC1 给了我一个不错的数值。但是当我测试 counter() 函数时,它给了我这个错误

欢迎任何建议或修复。我正在努力学习

【问题讨论】:

    标签: lua


    【解决方案1】:

    仔细查看您的错误,可以清楚地看到 Lua 在查找该名称的函数(或实际上任何其他变量)时遇到问题。如果你仔细观察,你会发现对readADC1 的调用是无效的,因为没有这样的函数。这是因为您定义的函数被称为ReadADC1。注意大写字母并记住变量在 Lua 中是区分大小写的。

    【讨论】:

    • 天啊。我怎么能错过呢。谢谢你。我已经为此工作了很长时间
    猜你喜欢
    • 1970-01-01
    • 2020-01-05
    • 2020-07-06
    • 2012-09-30
    • 2016-09-27
    • 1970-01-01
    • 2021-02-04
    • 1970-01-01
    • 2017-07-03
    相关资源
    最近更新 更多