简体   繁体   中英

Calling function from a different lua-file

I have this in 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

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:

...\\corona\\menu.lua:51:attempt to call field 'getLoggedIn' (a nil value)

The outprint is never reached. I'm working on Corona SDK and Sublime, the needed data from isLoggedIn() comes from a 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.

See PiL for other advanced methods.

you can also make seal class

by just writing below line at top of your class(databaseconnection.lua)

module(..., package.seeall)

than call your function in main.lua it will return the same value which you want to.

You can also get your data in this way.

require("databaseconnection") in your menu.lua file and call the get login function.

local abc = getLoggedIn()

print (abc)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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