lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


I was just thinking, when you write metamethods for an object that
also has __index and __newindex, you might want to use rawset and
rawget fairly often to avoid the overhead of invoking those
metamethods (since you probably don't need/want them for internal
methods such as these). However, each property you want to read/write
using rawset and rawget is another function call, which also has some
overhead.

You could avoid this by modifying rawset and rawget to accept multiple
parameters and return multiple values, i.e.:
local a, b, c = rawget(self, 'a', 'b', 'c')
rawset(self, 1, a, 2, b, 3, c) --or:
rawset(self, {a, b, c})

(As an example, I wrote a Vector3 class which provides __index and
__newindex to access the elements as v.x, v.y, v.z and v.r, v.g, v.b
for convenience, but actually stores them as v[1], v[2], v[3]. For
__add, __sub etc it's probably a lot more efficient not to go through
__index 6 times (3 per vector). Though, while writing I realized
__index isn't invoked for existing keys anyway, but that was where the
idea came from... Still, any code doing multiple rawget/rawset calls
on the same object could benefit from this.)

-- 
Sent from my toaster.