MHebes
|
  |
| Joined: 04 Jan 2013 |
| Total Posts: 2278 |
|
|
| 20 Aug 2013 10:51 AM |
So recently, I found out that if you run this code:
local t = {} t[Vector2.new(1,1)] = Vector2.new(2,2) t[Vector2.new(1,1)] = Vector2.new(3,3) table.foreach(t,print)
Those two Vector2.new(1,1)'s are actually counted as two separate indices, due to them both being userdata. This is a bit of an issue for me. Can anyone give me a suggestion as to how I can achieve the same-ish result? I need to have the indices contain an ordered pair, while still allowing me to overwrite them. I'm thinking an __newindex metatable might work?
~ Oh, I'm sorry, did I break your concentration? ~ |
|
|
| Report Abuse |
|
|
|
| 20 Aug 2013 10:59 AM |
Store them without using userdata, e.g.
t["1,1"] = Vector2.new(2,2);
If you need to convert between them, something like this, then:
function VecToStr(v) return v.x .. "," .. v.y end
function StrToVec(s) local p = s:find(","); return Vector2.new( tonumber( s:sub(1,p-1) ) , tonumber( s:sub(p+1) )) end
And then if you wanted it to be automatic, you could use __newindex and __index to apply those functions automatically. |
|
|
| Report Abuse |
|
|
MHebes
|
  |
| Joined: 04 Jan 2013 |
| Total Posts: 2278 |
|
|
| 20 Aug 2013 11:00 AM |
Didn't think to use strings at all ._. Thanks, that should probably work :D
~ Oh, I'm sorry, did I break your concentration? ~ |
|
|
| Report Abuse |
|
|
Newtrat
|
  |
| Joined: 13 Jun 2011 |
| Total Posts: 196 |
|
|
| 20 Aug 2013 11:01 AM |
You could try using tostring(Vector2.new(1,1)) as the key, rather than just the vector. Or, if you know there's some bound on the magnitude that won't be exceeded, you could use something like
function toInt(vec) return vec.x + 1000 * vec.y end t[toInt(Vector2.new(1,1)] = Vector2.new(2,2)
Basically this would be converting the vector into some non-userdata type before using it. |
|
|
| Report Abuse |
|
|