Jump to content

local table becomes global


Recommended Posts

In the following topic I have a problem were tables seem to be overwriting each other.

http://www.leadwerks.com/werkspace/topic/7133-script-and-local-usage/

 

Rick found the solution to this problem. Declaring lua tables like this:

Script.myTable = {}
--or
local myTable = {}

 

somehow makes them global and thus they will overwrite each other. Rick found out that you can solve this as follow:

 

Script.myTable = nil

function Script:Start()
self.myTable = {}
end

 

Still, it is odd that the first two methods are making tables global. This might be a bug?

Link to comment
Share on other sites

This is working as intended. If you declare a value outside a function, as a member of the script, it will be shared across all instances of the script. If you want a value to be unique for each instance of the script, declare it in the Start() function.

 

 

Link to comment
Share on other sites

Okay, thanks for answering.

 

*edit

Incorrect summary

So just to be clear: If I want variables that are local to a script an NOT global

 

Local

local pos
local drawColor

function Script:Start()
pos = Vec2(0,0)
drawColor = Vec3(255,0,0)

end

 

Global

local pos
local drawColor

function Script:Start()

end
Link to comment
Share on other sites

Shared across all instances of the script:

Script.mytable = {}

function Script:Start()
end

 

Unique for each instance:

function Script:Start()
  self.mytable = {}
end

 

Global variable:

mytable = {}

function Script:Start()
end

 

Global variable:

function Script:Start()
 mytable = {}
end

 

Local variable:

local mytable = {}

function Script:Start()
end

 

Local variable:

function Script:Start()
 local mytable = {}
end

  • Upvote 1

 

 

Link to comment
Share on other sites

Why are only tables defined outside a function like Script.mytable = {} shared across instances and normal variables aren't? ie. you can have different values per instance for normal variables defined as Script.myvar = 5, meaning defined like this isn't shared, but tables are shared. Seems odd.

 

[edit]

I tested an exposed variable like Script.health and set it's value differently between 4 different entities, but now that I say this when the game loads you must be making the same named variable behind the scenes for self so that self.health is unique now per instance.

  • Upvote 2
Link to comment
Share on other sites

Thanks for the clear post Josh. This helps me a lot. Perhaps it is a smart idea to document this in the scripts documentation.

 

I do agree with Rick on the consistency though. This has been very confusing and costed me a lot of time trying to figure out what I was doing wrong. Luckily, master Rick was able to see what was going on.

Link to comment
Share on other sites

Guest
This topic is now closed to further replies.
 Share

×
×
  • Create New...