Lua:如何在lua中将函数的返回值赋值给不同函数的本地值

我正在编写一个极其简单的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()函数时,它给了我错误

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

点赞
用户2487620
用户2487620

仔细查看您的错误,可以清楚地看到 Lua 无法找到该名称的函数(或者确切地说是任何其他变量)。如果您仔细看,就会发现对 readADC1 的调用无效,因为没有这样的函数。这是因为您定义的函数名为 ReadADC1。请注意大写字母,并记住在 Lua 中变量是区分大小写的。

看起来你的错误是因为 Lua 找不到该函数(或其他变量)。如果仔细查看,你会发现对 `readADC1` 的调用是非法的,因为没有这个函数。这是因为你定义的函数名是 `ReadADC1`。请注意大写字母,并记得 Lua 中的变量是区分大小写的。
2019-01-17 21:39:21