Quick Links: Download Gideros Studio | Gideros Documentation | Gideros community chat | DONATE
Is nil required if reference is lost? — Gideros Forum

Is nil required if reference is lost?

eezingeezing Member
edited May 2014 in General questions
Been working with Lua for a little while now and didn't really ponder the concept of garbage collection until now.

If we have the following:

local table = {a, b, c}

So the variable 'table' is just a reference to {a, b, c} and not actually a table.

So next, If we do this:

table = {4, 5, 6}

'table' is now referenced to {4, 5, 6} with reference to {a, b, c} lost. {a, b, c} will be garbage collected as any object not referenced will be collected, correct?

So, the last line in the following loop is not needed, correct?

local table

for i = 1, 100 do

table = makeSomeTable() -- Some function that returns a unique table

---[[ Use table in some manner here ]]---
---[[ Use table in some manner here ]]---
---[[ Use table in some manner here ]]---

table = nil <<----- pointless correct???

end

Or is there a benefit to nil for garbage collection?

Comments

  • HubertRonaldHubertRonald Member
    edited May 2014
    Hi @eezing
    I'm using your expression in my projects because
    "Before Older versions of Lua created empty tables with some pre-allocated slots to avoid this overhead when initializing small. However, this approach wastes memory".

    As an example, the next loop runs in 2.0 seconds:
    for i = 1, 1000000 do
      local a = {}
      a[1] = 1; a[2] = 2; a[3] = 3
    end
    If we create the tables with the right size, we reduce the run time to 0.7 seconds:
    for i = 1, 1000000 do
      local a = {true, true, true}
      a[1] = 1; a[2] = 2; a[3] = 3
    end
    If you know which will hosting the data table as well as its size, you can define something
    local a = {}
    for i = 1, 3 do --a,b,c, or more elements
       a[#a+1] = true -- it's more fast than table.insert(a,#a+1,true)
    end
    and after use this table for your operations

    If you want know how garbage collection works check this thread
    http://giderosmobile.com/forum/discussion/1423/class-inheritance-and-memory/p1

    I hope I've helped you

    P.S. samples was took of http://www.lua.org/gems/sample.pdf

    Likes: ar2rsawseen

    +1 -1 (+1 / -0 )Share on Facebook
Sign In or Register to comment.