Escaping
From GMod Wiki
Go to: Useful Information |
Lua: Escaping |
Description: | This article deals with the possible pitfalls and security hazards when embedding arbitrary text in strings. |
Original Author: | TomyLobo |
Created: | 14th April 2009 |
Contents |
Introduction
Certain characters have special meanings when used inside Lua strings. To use these anyway, you have to escape them.
How to escape
You have to put a backslash (\) in front of the character you wish to escape.
You only need to Escape certain special characters:
\ becomes \\
" becomes \" (in double-quoted strings)
' becomes \' (in single-quoted strings)
Dealing with unchecked strings
Be aware of the security risks of passing unchecked user input to functions that evaluate code (like SendLua).
To avoid these, use the %q option of Lua's string.format, which simply quotes and escapes everything into eval-safe form. (see the example below)
Examples
Say, you want to use SendLua to execute this line on the client:
print("Hello World\nHow're you?")
You'd have to escape the two double quotes and the \ from \n.
player:SendLua("print(\"Hello World\\nHow're you?\")")
SendLua with user data:
local filename = "hello.txt" local filetext = 'A string with "quotes".' player:SendLua(string.format("file.Write(%q,%q)",filename,filetext))
This would end up on the client as
file.Write("hello.txt","A string with \"quotes\".")