Question

I'm trying to learn the Lua language to develop plugins for my company's products. To help me learn (along with PiL book, Reference Manual, and numerous online resources), as I read I try to decipher current plugins we use.

One thing I've noticed is that local variables are listed at the very top and are not set to a specific value. For example: local SendVar and local EndVar.

But later on, many function's and local var's are used.

My question: I understand "Scope", global and local variables. But if there are no local function's within the plugin, are all local variables used within all functions?

I'm sorry for any confusion. But I'm trying to figure out how plugins are used within another program that uses other Lua plugins. I'm taking a wild guess when stating that unless local function's are otherwise stated, all local variables are used within that plugin file only.

Am I correct?

Was it helpful?

Solution

When in Lua you write a local statement, you are declaring that the following identifiers will denote local variables, whether or not those statements actually initializes the variables.

Moreover, local variables in Lua have block scope, i.e. they are visible in the block in which they are defined and in every enclosed block. Blocks are, for example, function bodies, then-end or else-end blocks, do-end blocks, etc.

Keep in mind, also, that variables in Lua don't have type, their value have.

-- declares `a` as a local variable (having no value, i.e. `nil` value)
local a   
-- declares `b` as a local variable having 2 as value
local b = 2  
-- declares `f` as local var having a function as value
local f = function(x) return x * x end  

do
    -- `a`, `b` and `f` are visible here, because this is a block enclosed 
    -- in the block where those vars were declared

    local aa = 2

end

-- `aa` is not visible here, because it was declared in an inner block  
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top