Page 1 of 2

Lua access parent scope var with same name as in local scope ?

Posted: Sun Dec 17, 2017 1:30 pm
by Davïd
Hello,

is there some way to access some var in parent scope var with same name as in local scope ?

A small example:

Code: Select all

local xPosition -- Parent scope Var

function setPosition(xPosition, yPosition)
        
        xPosition -- Access local var
        -- How to access parent scope xPosition ?
        
end
If it isn't possible I think I should rename my arguments but are there any naming convention for this in lua ?

TY

Re: Lua access parent scope var with same name as in local scope ?

Posted: Sun Dec 17, 2017 2:19 pm
by drunken_munki
http://lua-users.org/wiki/LuaScopingDiscussion

I'd take it as not possible.

The nearest local definition will be the variable determined at run time.

You could as you suggest rename your function variables to something different.

Or as an alternative (which I usually do) is create a table in the upper scope, which you can access that variable of the same name:

Code: Select all

local DATA = {xPosition} -- Parent scope Var
function setPosition(xPosition, yPosition)
        xPosition -- Access local var
	
        DATA.xPosition -- Access parent scope
end
This can also be a better strategy overall, since you contain all your true global or up-value locals in a single table, which in theory you could serialise or save out relatively easy (as well as import back in).

A total self applied convention is that I create these tables in upper case to identify their scope importance.

Re: Lua access parent scope var with same name as in local scope ?

Posted: Sun Dec 17, 2017 2:22 pm
by ivan
If it isn't possible I think I should rename my arguments but are there any naming convention for this in lua ?
Might be possible using the debug module, but I DON'T recommend it - especially as an alternative to naming your variables.
Just don't reuse the same variable names across scopes - it's confusing and can lead to bugs.
One common practice I have noticed is to put an underscore before any variables in the parent scope:

Code: Select all

local _xPosition -- Parent scope Var

function setPosition(xPosition, yPosition)
        
end

Re: Lua access parent scope var with same name as in local scope ?

Posted: Sun Dec 17, 2017 3:23 pm
by Davïd
Ok so it's not possible.

I will go with _ prefix then. Some people does that in other laguages too. I was wondering cause it's also used for throw away vars like in

Code: Select all

for _,v in ipairs(t) do print(v) end
@drunken_munki To me xPosition is an object private field and I feel more natural to put everything in separate vars. But maybe it could be done in a better way with a table named private or something like this. I have to think about it :huh:

Here is how it look like for now :

Code: Select all

local Object = {}

--[[
Game object is base for object updating each frame
@return table : new object
]]

function Object.new()
    
    local self = {}
    
    --[[
    Publics vars
    --------------------------------]]
    
    self.foo = 'bar'
    
    --[[
    Locales vars
    --------------------------------]]
    
    -- Positions    
    local _xPosition = -1 -- X position on world
    local _yPosition = -1 -- Y position on world
    local _xOriginPosition = -1 -- X origin position on world
    local _yOriginPosition = -1 -- Y origin position on world
    
    --[[
    Auto called methods
    --------------------------------]]
    
    --[[
    Init
    ]]
    
--    function self.init()
--    end
    
    --[[
    Sleep
    ]]
    
--    function self.sleep()
--    end

    --[[
    Wake up
    ]]
    
--    function self.wakeUp()
--    end
    
    --[[
    Update
    ]]
    
--    function self.update()
--    end
    
    --[[
    Fixed update
    ]]
    
--    function self.fixedUpdate()        
--    end
    
    --[[
    Draw
    ]]
    
--    function self.draw()        
--    end

    --[[
    Methods
    --------------------------------]]
    
    --[[
    Set position
    @param int xPosition
    @param int yPosition
    ]]

    function self.setPosition(xPosition, yPosition)
        
        _xPosition = xPosition
        _yPosition = yPosition      
        
    end
    
    --[[
    Get position
    @return table : {_xPosition, _yPosition}
    ]]

    function self.getPosition()
        
        return {_xPosition, _yPosition}
        
    end

    return self
    
end

return Object
I didn't think about a way to serialise objects. It sure could be useful.

Re: Lua access parent scope var with same name as in local scope ?

Posted: Sun Dec 17, 2017 3:51 pm
by ivan
also used for throw away vars
In a way, they are. "_xPosition" cannot be accessed outside of that file so it's sort of an "internal" variable.

Your code looks fine, note that if you want to do OO using closures
you can just return a function
and you don't need to use self or the colon operator(":")

Code: Select all

return function(id)
  local _x, _y = 0, 0
  local obj = {}
  function obj.set(x, y)
    _x, _y = x, y
  end
  function obj.get()
    return _x, _y
  end
  return obj
end
Don't do stuff like:

Code: Select all

return {_xPosition, _yPosition}
Just return multiple values:

Code: Select all

return _xPosition, _yPosition

Re: Lua access parent scope var with same name as in local scope ?

Posted: Sun Dec 17, 2017 4:46 pm
by Davïd
ivan wrote: Sun Dec 17, 2017 3:51 pm Your code looks fine, note that if you want to do OO using closures
you can just return a function
and you don't need to use self or the colon operator(":")

Code: Select all

return function(id)
  local _x, _y = 0, 0
  local obj = {}
  function obj.set(x, y)
    _x, _y = x, y
  end
  function obj.get()
    return _x, _y
  end
  return obj
end
Some one told me that it was a bad idea to use self like I do but didn't get why? The way you do it look more concise indeed.

I plan to do some kind of inheritance. For example a Character will look like :

Code: Select all

local Object = {}

--[[
Object definition
@return table : new Object
]]

function Object.new()
    
    local self = require('script.gameobject').new() -- this is the previous code I posted above
    
    --[[
    Update
    ]]
    
    function self.update()
        
        print('update')
        
    end
    
    --[[
    Draw
    ]]
    
    function self.draw()
        
        print('draw')
        
    end
    
    --[[
    Draw
    ]]
    
    function self.move()
        
        print('move')
        
    end
    
    return self
    
end

return Object
Is this doable with the code you posted ?
And what id point in function(id) ?
And can you have multiple instance of an object ?

Sorry for that much questions :ultrahappy:
ivan wrote: Sun Dec 17, 2017 3:51 pm Don't do stuff like:

Code: Select all

return {_xPosition, _yPosition}
Just return multiple values:

Code: Select all

return _xPosition, _yPosition
Ok, didn't know you could return multiple value like this. It look better.

Re: Lua access parent scope var with same name as in local scope ?

Posted: Sun Dec 17, 2017 7:26 pm
by ivan
I plan to do some kind of inheritance
metatables are typically the way to go - if you plan to have inheritance.
Is this doable with the code you posted ?
There are different ways to program OO in Lua.
The examples we have posted so far are based on closures.
Inheritance is much easier to implement using metatables.
And what id point in function(id) ?
No real point, it was just an example.
And can you have multiple instance of an object ?
Yes.

Re: Lua access parent scope var with same name as in local scope ?

Posted: Sun Dec 17, 2017 7:45 pm
by Davïd
I already read about metatable but I wont get why they are needed and how do they work for now. I will get back to it.

Thank you.

Re: Lua access parent scope var with same name as in local scope ?

Posted: Mon Dec 18, 2017 6:50 pm
by Davïd
Ok, I changed my code with the closure you gave me and it look nicer. :nyu:

I tried some example with metatable but to me it look over complicated. Also I think it better fit with real OOP (with multiple inheritance and stuff like that) but I m not sure for oriented prototype code ?

Re: Lua access parent scope var with same name as in local scope ?

Posted: Mon Dec 18, 2017 7:07 pm
by ivan
There is no "real" OOP in Lua, it all depends on what you are trying to do.
Closures are simple, fast and work best for long-lived objects.
If you want inheritance, then metatables are the way to go. It doesn't have to be complicated (see my super simple lib: https://github.com/2dengine/oo.lua )
For multiple inheritance, then you probably want something like mixins (see kikito's middleclass: https://github.com/kikito/middleclass )
Personally, I try to keep my code simple and clear, so I avoid OOP as much as possible.