lua-users home
lua-l archive

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


Jamie Webb Wrote:
> As it is, it wouldn't work if you used the same function more
> than once in an
> expression.

I actually beg to differ (provided we are not dealing with preemptive
multithreading). Unfortunately, my originally proposed code had an obvious
typo, please find the correction below:

local vector3_add_rtn = {}
local function vector3_add(self, o)
   for i=1,3 do
      vector3_add_rtn[i] = self[i] + o[i] -- Line in question
   end
   return vector3_add_rtn; -- Correction performed here
end

The idea is that only two vectors can be added at any given time even in
complex expressions. In cases where we have multiple vectors being added
(i.e. v1 + v2 + v3 etc.) we will have intermediate results stored in the
upvalue. The next invocation of the __add metamethod will have this
temporary result as one of the arguments. Therefore the assignment marked
with the comment 'Line in question' becomes effectively either

vector3_add_rtn[i] = vector3_add_rtn[i] + o[i]

or

vector3_add_rtn[i] = self[i] + vector3_add_rtn[i]

I can't see anything wrong with that in a single threaded application (using
Lua coroutines should still be OK).

Marius