Calling function from a different lua-file
Asked Answered
S

3

10

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?

Selimah answered 10/3, 2014 at 14:31 Comment(0)
L
11

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.

Letsou answered 10/3, 2014 at 15:6 Comment(0)
M
0

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)

Mic answered 20/3, 2014 at 6:57 Comment(0)
C
-1

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.

Colyer answered 14/3, 2014 at 8:9 Comment(1)
Deprecated now. Unavailable in latest LUA.Wieche

© 2022 - 2024 — McMap. All rights reserved.