benwad
benwad

Reputation: 6594

Detecting if a variable can be printed in Lua

I've got a variable that could be a number of types - sometimes it's a string, sometimes a number, table or bool. I'm trying to print out the value of the variable each time like this:

print("v: "..v)

with v being my variable. Problem is, when I get a value that can't be concatenated I get this error:

myscript.lua:79: attempt to concatenate a table value

I've tried changing it to this in case it manages to detect whether or not the variable can be printed:

print("v: "..(v or "<can't be printed>"))

but I had the same problem there. Is there some sort of function I can use to determine if a variable can be concatenated to a string, or a better way of printing out variables?

Upvotes: 4

Views: 4943

Answers (2)

John Payne
John Payne

Reputation: 116

tostring(v) works for all possible v values (including nil). So writing your line as:

print( "v: " .. tostring( v ) )

will always work.

Alternatively you could have a look at type( v ) and if its "string" print it, otherwise print something else (if that's what you want).

Upvotes: 6

Supr
Supr

Reputation: 19022

You can provide the values as separate arguments to print:

print("v:", v)

This would print something like

v:  table: 006CE900

Not necessarily the most useful, but better than a crash if it's just for debugging purposes.

See here for information on more useful table printing.

Upvotes: 8

Related Questions