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

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Davïd
Prole
Posts: 12
Joined: Sun Jan 29, 2017 4:12 pm

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

Post 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
drunken_munki
Party member
Posts: 134
Joined: Tue Mar 29, 2011 11:05 pm

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

Post 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.
User avatar
ivan
Party member
Posts: 1915
Joined: Fri Mar 07, 2008 1:39 pm
Contact:

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

Post 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
Davïd
Prole
Posts: 12
Joined: Sun Jan 29, 2017 4:12 pm

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

Post 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.
User avatar
ivan
Party member
Posts: 1915
Joined: Fri Mar 07, 2008 1:39 pm
Contact:

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

Post 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
Davïd
Prole
Posts: 12
Joined: Sun Jan 29, 2017 4:12 pm

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

Post 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.
User avatar
ivan
Party member
Posts: 1915
Joined: Fri Mar 07, 2008 1:39 pm
Contact:

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

Post 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.
Davïd
Prole
Posts: 12
Joined: Sun Jan 29, 2017 4:12 pm

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

Post 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.
Davïd
Prole
Posts: 12
Joined: Sun Jan 29, 2017 4:12 pm

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

Post 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 ?
User avatar
ivan
Party member
Posts: 1915
Joined: Fri Mar 07, 2008 1:39 pm
Contact:

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

Post 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.
Last edited by ivan on Wed Dec 15, 2021 11:31 am, edited 1 time in total.
Post Reply

Who is online

Users browsing this forum: Google [Bot], pgimeno and 0 guests