Escaping

From GMod Wiki

Jump to: navigation, search
Icon-info.png Go to:
Useful Information
Lua: Escaping
Page white text.png Description:This article deals with the possible pitfalls and security hazards when embedding arbitrary text in strings.
link=User:TomyLobo Original Author:TomyLobo
Calendar.png 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\".")
Personal tools
Namespaces
Variants
Actions
Navigation
Lua Scripting
Functions
Hooks
Toolbox