Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calculating string length causes confustion

Tags:

lua

I am confused by the following output:

local a = "string"
print(a.len)        -- function: 0xc8a8f0
print(a.len(a))     -- 6
print(len(a)) 
--[[
/home/pi/test/wxlua/wxLua/ZeroBraneStudio/bin/linux/armhf/lua: /home/pi/Desktop/untitled.lua:4: attempt to call global 'len' (a nil value)
stack traceback:
    /home/pi/Desktop/untitled.lua:4: in main chunk
    [C]: ?
]]

What is the proper way to calculate a string length in Lua?

Thank you in advance,

like image 769
user977828 Avatar asked May 17 '26 13:05

user977828


1 Answers

You can use:

a = "string"
string.len(a)

Or:

a = "string"
a:len()

Or:

a = "string"
#a

EDIT: your original code is not idiomatic but is also working

> a = "string"
> a.len
function: 0000000065ba16e0
> a.len(a)
6

The string a is linked to a table (named metatable) containing all the methods, including len.

A method is just a function, taking the string as the first parameter.

function a.len (string) .... end

You can call this function, a.len("test") just like a normal function. Lua has a special syntax to make it easier to write. You can use this special syntax and write a:len(), it will be equivalent to a.len(a).

like image 73
Robert Avatar answered May 21 '26 21:05

Robert