lua-users home
lua-l archive

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


On Monday 27, Joshua Jensen wrote:
> ----- Original Message -----
> From: Ian Millington
> Date: 6/26/2011 5:04 PM
> 
> > A while back I posted a commercial job offer for someone to help add
> > in-place mutation operators to Lua (+=, -=, *=, /=, %= and ^=). My
> > domain is in a scripting language for games, and a good deal of the
> > lua scripts consist of changing variable values, such as:
> > 
> > target.health -= 2
> > player.ammo.shells -= 1
> > 
> > so this saves a *lot* of typing.
> 
> This just made my day.
> 
> It isn't just about typing.  It's also about performance.  When written
> like:
> 
>          player.ammo.shells = player.ammo.shells - 1
> 
> Lua must:
> 
> * Look up player.
> * Look up ammo.
> * Look up shells.
> * Subtract 1.
> * Look up player.
> * Look up ammo.
> * Set via hash the shells key to be the result of the subtraction.

That is almost right, the last two lookups come before the 'substract' 
operation.

Opcodes:
1 GETGLOBAL	0 -1     ; player
2 GETTABLE 	0 0 -2  ; "ammo"
3 GETGLOBAL	1 -1     ; player
4 GETTABLE 	1 1 -2  ; "ammo"
5 GETTABLE 	1 1 -3  ; "shells"
6 SUB     	        1 1 -4  ; - 1
7 SETTABLE 	0 -3 1  ; "shells" -

> 
> When written as "player.ammo.shells -= 1", Lua must:
> 
> * Look up player.
> * Look up ammo.
> * Look up shells.
> * Subtract 1.
> * Directly store the result.
> 
> Hooray!  (I hope this is how the patch works, anyway...)

The new syntax saves two lookups(one global, one table) in this example.

Opcodes:
1 GETGLOBAL	0 -1     ; player
2 GETTABLE 	0 0 -2  ; "ammo"
3 GETTABLE 	1 0 -3  ; "shells"
4 SUB_EQ   	1 -4
5 SETTABLE 	0 -3 1  ; "shells" -

The last operation is still a normal "SETTABLE".  No special support for 
modifying a table slot directly, doing so wouldn't work with tables/userdata 
that have __index/__newindex metamethods.

> I have just pushed this to the LuaPlus repository on GitHub, #ifdef'ed
> as LUA_MUTATION_OPERATORS.
> 
> Josh


-- 
Robert G. Jakabosky