Ouroborus
Ouroborus

Reputation: 16886

Lua quirk with s:format()

It seems like this syntax should work but doesn't:

> print "%i":format(42)
%i  
[string "return print "%i":format(42)"]:1: attempt to index a nil value

This also fails:

> print ("%i":format(42))
[string "print ("%i":format(42))"]:1: ')' expected near ':'

This sort of works:

> print (("%i"):format(42))
42  
=> [string "return print ("%i"):format(42)"]:1: attempt to index a nil value

Can somebody explain what's going on and tell me how it's supposed to be done?

(I'm aware of string.format("%i", 42) but I'm trying out this other syntax shown in the docs.)

Edit: Further testing shows this is partially an issue with repl.it. Running the interpreter locally doesn't show any error for the last example.

Upvotes: 0

Views: 88

Answers (1)

lhf
lhf

Reputation: 72342

This is not related to string.format, it's a general syntax feature of Lua: in method calls on complicated expressions, you need to enclose the expression in parentheses.

See prefixexp in the Lua BNF:

prefixexp ::= var | functioncall | ‘(’ exp ‘)’
functioncall ::=  prefixexp args | prefixexp ‘:’ Name args 

Upvotes: 2

Related Questions