davisdude wrote:
From my understanding, that's what metatables are for. Also, I tested
Code: Select all
gun_1 = gun.create( false, 100, 100, 100, 100, 100 ),
gun_2 = gun.create(),
and it had already inherited all the traits of the
Code: Select all
gun = { automatic = true, clip_size = 32, x = 0, y = 0, w = 100, h = 100 }
portion.
My bad, you are definitely right on this.
I did not not noticed that default values were already defined in the
gun table prototype. Just take into account that those properties are not available on instantiation, but
right at the moment you will need them. Practically it doesn't raise any issue, but it is good to know that to fully understand what metatables does.
For instance, you can try the following after creating a new gun object.
Code: Select all
local gun_A = gun.create()
-- Print all of its properties and values
for k,v in pairs(gun_A) do print(k,v) end
-- Check for a property
print(gun_A.automatic) --> true
-- Print all of its properties and values again
for k,v in pairs(gun_A) do print(k,v) end]
-- and so on
davisdude wrote:
I didn't know pairs was slower...
Indeed it is. But it won't make any real difference unless you are dealing with a large number of items when iterating.
The thing is,
ipairs iterates on the assumption that the collection you are cycling through contains elements sorted numerically with integers, while
pairs does not follow any particular order. Basically, it is a common behavior for Lua users to use
ipairs for array-like tables (
pairs will also work here).
Code: Select all
local t = {'a', 'b', true, 4}
for k,v in ipairs(t) do
print(k,v)
end
And pairs for map-like tables, where entries are not likely to be indexed with keys (
ipairs will just fail on such tables).
Code: Select all
local t = {
a = 1,
b = 2,
c = 3
}
for k,v in pairs(t) do
print(k,v)
end
If you want to dig deeper, see
TableTutorial.
davisdude wrote:
Finally, isn't the
portion of your arbitrary, since you insert it in to gun anyway?
Well, not exactly. In general, anytime one inits a new objects, he is likely to store this object in a variable.
That is the reason for what the factory function should return something. But right before that, it also internally registers this new instance inside a collection, which is very convenient too if one needs to cycle through all those instances later on.
On the other hand, this one would have been terrific:
Code: Select all
gun.create(....) -- Create a new gun object, which will be stored last in the collection
local myNewGun = #guns -- Get the last gun created.