lua-users home
lua-l archive

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


It was thus said that the Great Mason Mackaman once stated:
> Thanks, but that is over my head lol.

  Lua code is compiled into an internal format (the Lua Virtual Machine or
Lua VM) before it's executed.  This is an important thing to remember---Lua
code is compiled to some internal format.

  With that out of the way, there are four ways of getting the length of a
string in Lua:

	local x = "a string"
	local y

	y = #x			-- number 1
	y = x:len()		-- number 2
	y = x.len(x)		-- number 3
	y = string.len(x)	-- number 4

  Method 1 uses one VM instruction [1] to calculate the length of the string
(I'm ignoring the instructions that make up the assignment; they differ
depending on if the assignment goes to a global or a local [2]) and is thus,
the fastest method.

  Method 2 uses two VM instructions---one to obtain the "len" function via
the string's metatable, and one instruction to call the function; the
agument (x in this case) is inherent in how this works.

  Method 3 uses three VM instructions---one to obtain the "len" function via
the strings metatable, one to get the argument to the function (x in this
case) and the third to call the function.

  Method 4 uses four VM instructions---one to get the global "string" table
[2], a second to obtain the "len" function from that table, the third to get
the argument to the function, and the fourth to call the function.

  -spc

[1]	The stock Lua interpreter.  The details differ for LuaJIT, but
	overall, the trend is similar.

[2]	Technically, to a field in a table (since "globals" are stored in a
	special table internally).