Lua:在自己的模块中调用函数

时间:2016-02-16 17:05:13

标签: lua

我为RTC创建了一个模块。它看起来像这样:

local moduleName = ...
local M = {}
_G[moduleName] = M

---------- Local variables ---------------------
local id = 0
local address = 0x68


---------- Helper functions --------------------
local function bcdToDec(val)
    local hl=bit.rshift(val, 4)
    local hh=bit.band(val,0xf)
    local hr = string.format("%d%d", hl, hh)
  return string.format("%d%d", hl, hh)
end

local function decToBcd(val)
   local d = string.format("%d",tonumber(val / 10))
   local d1 = tonumber(d*10)
   local d2 = val - d1
   return tonumber(d*16+d2)
end

---------- Module functions --------------------
function M.Init(sda, scl)
    i2c.setup(id, sda, scl, i2c.SLOW)
end


function M.PrintTime()
    i2c.start(id)
    i2c.address(id, address, i2c.TRANSMITTER)
    i2c.write(id, 0x00)
    i2c.stop(id)
    i2c.start(id)
    i2c.address(id, address, i2c.RECEIVER)
    c=i2c.read(id, 7)
    i2c.stop(id)
    s = bcdToDec(string.byte(c,1))
    m = bcdToDec(string.byte(c,2))
    h = bcdToDec(string.byte(c,3))

    time=string.format(" %s:%s:%s", h, m, s)
    print(time);
end

function M.PrintDate()
    i2c.start(id)
    i2c.address(id, address, i2c.TRANSMITTER)
    i2c.write(id, 0x00)
    i2c.stop(id)
    i2c.start(id)
    i2c.address(id, address, i2c.RECEIVER)
    c=i2c.read(id, 7)
    i2c.stop(id)
    s = bcdToDec(string.byte(c,1))
    m = bcdToDec(string.byte(c,2))
    h = bcdToDec(string.byte(c,3))
    wkd = bcdToDec(string.byte(c,4))
    day = bcdToDec(string.byte(c,5))
    month = bcdToDec(string.byte(c,6))
    year = bcdToDec(string.byte(c,7))

    time=string.format(" %s.%s.%s", day, month, year)
    print(time);
end

return M

我将此文件保存为" ds3231_m.lua"。从另一个文件调用函数的工作方式如下:

m = require 'ds3231_m'
m.Init(2,1)   --sda, scl = 2, 1
m.PrintTime()
--m.PrintDate()
package.loaded.ds3231_m = Nil

以及

m = require 'ds3231_m'
m.Init(2,1)   --sda, scl = 2, 1
--m.PrintTime()
m.PrintDate()
package.loaded.ds3231_m = Nil

但是当我尝试调用这两个函数时:

m = require 'ds3231_m'
m.Init(2,1)   --sda, scl = 2, 1
m.PrintTime()
m.PrintDate()
package.loaded.ds3231_m = Nil

我收到错误:

test.lua:4: attempt to call field 'PrintDate' (a nil value)

谁能告诉我出了什么问题?

非常感谢你!

此致

1 个答案:

答案 0 :(得分:4)

在PrintTime(和PrintDate)中你正在做m = something。这会覆盖m = require(...) m 。 你应该在这些函数中使用locals:

function M.PrintTime()
    i2c.start(id)
    i2c.address(id, address, i2c.TRANSMITTER)
    i2c.write(id, 0x00)
    i2c.stop(id)
    i2c.start(id)
    i2c.address(id, address, i2c.RECEIVER)
    local c=i2c.read(id, 7)
    i2c.stop(id)
    local s = bcdToDec(string.byte(c,1))
    local m = bcdToDec(string.byte(c,2))
    local h = bcdToDec(string.byte(c,3))

    local time=string.format(" %s:%s:%s", h, m, s)
    print(time);
end

这样,你就不会编辑任何全局变量。对PrintDate也这样做。

(如果您other_name_than_m = require(...)确实没有注意到,print(m)仍会打印一个数字,即分数的分钟数