简体   繁体   English

从不同的lua文件调用函数

[英]Calling function from a different lua-file

I have this in menu.lua 我在menu.lua中有这个

local db = require "databaseconnection"
...
local function onEndBtnRelease()
    local thisandthat = db.getLoggedIn()
    native.showAlert( "Corona SDK", thisandthat.." teststring", { "OK" } )
end
...

and this in databaseconnection.lua 这在databaseconnection.lua中

local function getLoggedIn()
    print("Test")
    --[[...
    ]]--

    return "some data"
end 

The only thing I want is that String ( "some data" ) from getLoggedIn() , but all I get is an error: 我唯一想要的是来自getLoggedIn() String( "some data" getLoggedIn() ,但我得到的只是一个错误:

...\\corona\\menu.lua:51:attempt to call field 'getLoggedIn' (a nil value) ... \\ corona \\ menu.lua:51:尝试调用字段'getLoggedIn'(零值)

The outprint is never reached. 永远不会达到外包。 I'm working on Corona SDK and Sublime, the needed data from isLoggedIn() comes from a sqlite-request. 我正在使用Corona SDK和Sublime,来自isLoggedIn()的所需数据来自sqlite-request。 How can I reach that function? 我怎样才能达到这个功能?

One direct way to write a module is to return a table that includes the functions you need: 编写模块的一种直接方法是返回一个包含所需函数的表:

local M = {}

function M.getLoggedIn()
    print("Test")
    --...
    return "some data"
end 

return M

Note that the function needs to be non- local , or it would be private. 请注意,该函数必须是非local ,否则它将是私有的。

See PiL for other advanced methods. 有关其他高级方法,请参阅PiL

you can also make seal class 你也可以上班

by just writing below line at top of your class(databaseconnection.lua) 只需在类的顶部写下面的行(databaseconnection.lua)

module(..., package.seeall)

than call your function in main.lua it will return the same value which you want to. 而不是在main.lua中调用您的函数,它将返回您想要的相同值。

You can also get your data in this way. 您也可以通过这种方式获取数据。

require("databaseconnection") in your menu.lua file and call the get login function. 在menu.lua文件中输入require(“databaseconnection”)并调用get login函数。

local abc = getLoggedIn() local abc = getLoggedIn()

print (abc) 打印(abc)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM