Frage

I am confused as to how function is declared in lua. What i want to know is the order the function definition is in the file. In my example, sample 1 works where as sample 2 wouldn't compile.

Sample 1

--This works, sample 1
function finddir(lpath)
local localfs =  require "luci.fs"

if localfs.isdirectory(lpath) then
  print "we have directory"
  else
    print "Directory not found"
    end
end

**local ltest = finddir("/proc/net/")**
-- END --

Sample 2

--This Sample fails to compile, Sample 2
**local ltest = finddir("/proc/net/")**

function finddir(lpath)
local localfs =  require "luci.fs"

if localfs.isdirectory(lpath) then
  print "we have directory"
  else
    print "Directory not found"
    end
end
-- END --
War es hilfreich?

Lösung

Functions in Lua are first-class values.

In the first example, the function is defined, in another word, the variable finddir has a value of type function. So you can call it.

In the second example, the function has not been defined when you call it, in another word, the varialbe finddir has a value nil, thus you can't call it.

It's not that different with other types, e.g:

n = 42
local a = n + 3  --fine

vs

local a = n + 3  --error, n is nil
n = 42
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top