Forum

> > CS2D > Scripts > Common Mistakes by Scripter
Forums overviewCS2D overview Scripts overviewLog in to reply

English Common Mistakes by Scripter

13 replies
To the start Previous 1 Next To the start

old Common Mistakes by Scripter

MikuAuahDark
User Off Offline

Quote
Here is most common mistakes by scripter(maybe not all of them and maybe not very common)

1. Too Many/Less ends
Example:
1
2
3
4
5
6
addhook("say","foo")
function foo(bar,baz)
if baz=="Hello World!" then
msg2(bar,"Hello World!")
return 1
end
Code above is missing 1 end. To fix it, you may need to tab your code properly and fix it
1
2
3
4
5
6
7
addhook("say","foo")
function foo(bar,baz)
	if baz=="Hello World!" then
		msg2(bar,"Hello World!")
		return 1
	end
end	-- this is it
Error Message(less ends): LUA ERROR: filename:end of line: 'end' expected (to close 'function' at line function line) near '<eof>'
Error Message(too many ends): LUA ERROR: filename:line number: '<eof>' expected near 'end'


2. Different file encoding.
Note, CS2D only able to handle ANSI encoded file corrently. UTF-8 w/o BOM threats some symbol to another symbol(example copyright sign into Â). UTF-8 and UTF-16(both LE & BE)simply throws LUA ERROR.
Solution: Change file encoding to ANSI. It doesn't necessary to encode file not in ANSI
Please not that all error message below always points to line 1
Error Message(UTF-8): LUA ERROR: filename:1: unexpected symbol near 'ï'
Error Message(UTF-16 LE): LUA ERROR: filename:1: unexpected symbol near 'ÿ'
Error Message(UTF-16 BE): LUA ERROR: filename:1: unexpected symbol near 'þ'


3. Return 1 doesn't work a.k.a conflicting hooks
Causes: there's more than 1 function using hooks that acept return values
Solution: By adding priority number as third argument in cs2d lua cmd addhook(read carefully) or combine the function into 1.
Info: Hooks that accept return values: cs2d lua hook bombdefuse, cs2d lua hook bombexplode, cs2d lua hook bombplant, cs2d lua hook build, cs2d lua hook buildattempt, cs2d lua hook buy, cs2d lua hook die, cs2d lua hook dominate, cs2d lua hook drop, cs2d lua hook flagcapture, cs2d lua hook flagtake, cs2d lua hook hit, cs2d lua hook hitzone, cs2d lua hook log, cs2d lua hook name, cs2d lua hook objectdamage, cs2d lua hook objectupgrade, cs2d lua hook parse, cs2d lua hook radio, cs2d lua hook rcon, cs2d lua hook say, cs2d lua hook sayteam, cs2d lua hook spawn, cs2d lua hook team, cs2d lua hook trigger, cs2d lua hook triggerentity, and cs2d lua hook walkover

If you want to add more, feel free to comment
edited 1×, last 12.06.14 12:05:47 pm

old Re: Common Mistakes by Scripter

Apache uwu
User Off Offline

Quote
4. Attempting to access table indices at zero.

1
2
3
4
5
local tbl = {}
table.insert(tbl, "hello")
table.insert(tbl, "world")

print(tbl[0]) --nil

It's frustrating because LUA also doesn't raise an error, it just returns nil.

5. Comparing cs2d lua cmd game to numbers.

1
2
3
if game("ct_score") == 5 then
    print("CTs have 5, they win!")
end

All values returned by game will be a string, so you'll want to cast using tonumber() if you want to compare mathematically.

6. Attempting to mass comment code with [[ ]] as quotations.

1
2
3
4
5
6
7
8
9
10
11
12
13
--[[

addhook([[serveraction]],[[servaction]])
function servaction(id,acti)
    local angle = math.rad(math.abs( rot + 90 )) - math.pi
    local x = player(id,[[x]]) + math.cos(angle) * 25
    local y = player(id,[[y]]) + math.sin(angle) * 25
    if x > 0 and y > 0 and x < map([[xsize]]) * 32 and y < map([[ysize]]) * 32 then
        parse([[setpos ]]..id..[[ ]]..x..[[ ]]..y)
    end
end

--]]

LUA can load string with the single, double or with double square brackets as strings. When scripters decide to use square brackets, it's difficult to comment over multiple lines. (It's common for a language to disallow nested block commenting)

old Re: Common Mistakes by Scripter

EngiN33R
Moderator Off Offline

Quote
@user Apache uwu: Top tip for #6:

1
2
3
4
5
6
7
8
9
10
11
12
13
--[=[

addhook([[serveraction]],[[servaction]])
function servaction(id,acti)
    local angle = math.rad(math.abs( rot + 90 )) - math.pi
    local x = player(id,[[x]]) + math.cos(angle) * 25
    local y = player(id,[[y]]) + math.sin(angle) * 25
    if x > 0 and y > 0 and x < map([[xsize]]) * 32 and y < map([[ysize]]) * 32 then
        parse([[setpos ]]..id..[[ ]]..x..[[ ]]..y)
    end
end

]=]

Lua supports a theoretically endless number of quotations, since it's possible to insert any number of equal signs (=) between double square brackets and it will still be valid string literal syntax.

----------------

7. Using a table as default value for initArray() or similar

1
2
3
4
5
6
7
8
9
function initArray(n, v)
	local t = {}
	for i = 1, n do
		t[i] = v
	end
	return t
end

player_inventory = initArray(32, {})

This one is something I was guilty of doing in the (now) distant past. This code will create one table (since the table constructor {} is only called once) and share it across 32 players. In this case, it means if you modify the inventory of one player, you will also modify the inventory of everyone else in the same way.

Solution: for God's sake, don't use initArray. But if you must, make a new initArray function that creates a table of tables:

1
2
3
4
5
6
7
8
9
function initArray2(n)
	local t = {}
	for i = 1, n do
		t[i] = {}
	end
	return t
end

player_inventory = initArray2(32)

This way, a new table is created 32 times for each player without conflicts or overlap.

old Re: Common Mistakes by Scripter

MikuAuahDark
User Off Offline

Quote
@user Apache uwu: Number 4: That's because LUA Index start with 1

bdw, moderator, can you make this thread always stick on top if possible?

---------------

8. Invalid arguments
Example:
1
2
3
4
addhook("second","foo")
function foo(id)
	msg2(id,"Second has passed!")
end
id will be nil. and throw LUA ERROR.
Solution: Read the hook documentation for more info. cs2d lua hook second doesn't pass any arguments, so
1
2
3
4
5
6
addhook("second","foo")
function foo()
	for _,id in pairs(player(0,"table")) do
		msg2(id,"Second has passed!")
	end
end
code above would work as expected.

old Re: Common Mistakes by Scripter

Infinite Rain
Reviewer Off Offline

Quote
9.
Declaring a variable with a name which is already used by CS2D.
1
player = {}

If you do that, you will no longer be able to use player(id, "value") function. To avoid that either pick a different name or make a global table for your script.
1
_player = {}
1
2
3
scr = {
	player = {}
}

10.
Writing code in a function after the "return" keyword.
1
2
3
4
Add = function(x, y)
	return x + y
	print('Function "Add" was executed.')
end

The "return" keyword aborts the script execution inside a function. That means any code after "return" will not be run. In order to avoid that put your code before "return" instead of putting it after the "return".
1
2
3
4
Add = function(x, y)
	print('Function "Add" was executed.')
	return x + y
end
edited 1×, last 11.06.14 02:40:06 pm

old Re: Common Mistakes by Scripter

Dousea
User Off Offline

Quote
@user TimeQuesT: I thought it is "Common Mistakes by Scripter".

11. String to number conversion when executing with parameter for non-built-in CS2D function at cs2d lua cmd timer.
1
2
3
4
5
6
7
list = {}

timer (1000, "testtimer", 1)

function testtimer (number)
	list[number] = number
end
cs2d lua cmd timer makes parameter's type changed to string, if it's not string. Value at index 1 in list table contains nothing. Value at index "1" contains "1". When you call list[1], it throws you an error, I guess. Otherwise when you call list["1"] (with string), it returns "1". It needs string to number conversion by using tonumber function.
1
2
3
4
5
6
7
list = {}

timer (1000, "testtimer", 1)

function testtimer (number)
	list[tonumber (number)] = number
end
So value at index 1 in list table will be "1", not at index "1". The value is "1" because it doesn't converted using tonumber. Or if you want both of them as number,
1
2
3
4
5
6
7
8
list = {}

timer (1000, "testtimer", 1)

function testtimer (number)
	number = tonumber (number)
	list[number] = number
end

old Re: Common Mistakes by Scripter

MikuAuahDark
User Off Offline

Quote
12. Comparing with another type of value
1
2
3
4
number=5
if number==table then
	print("miracle happend!")
end
it's always returns false unless you're using metatables


13. Using cs2d cmd equip in cs2d lua hook spawn
1
2
3
4
addhook("spawn","foo")
function foo(id)
	parse("equip "..id.." 32")
end
cs2d lua hook spawn has written
Attention: Do NEVER use the "equip" command within this hook! It will probably lead to problems! Use the return value of the hook instead!

So the solution is
1
2
3
4
addhook("spawn","foo")
function foo(id)
	return "32"
end

old Re: Common Mistakes by Scripter

_Yank
User Off Offline

Quote
14. Creating arrays with unnecessary itens when the server maxium players isn't 32
1
playerTable = initArray(32, {})
It would be better if...
1
2
local maxPL = tonumber(game("sv_maxplayers"))
playerTable = initArray(maxPL, {})
And, if the maxium player isn't going to be constant,
1
2
3
4
5
6
7
addhook("parse","updateTable")
function updateTable(cmd)
	if cmd:sub(1, 13) == "sv_maxplayers" then
		local new = tonumber(cmd:sub(15)) - #playerTable
		for i = 1, new do table.insert(playerTable, {}) end
	end
end

15. Using quotes while you prefer to use doublequotes for the cs2d lua cmd parse command.
1
2
myName = "Yank"
parse('hudtxt2 1 1 "Your name is '..myName..'" 320 240 1')
It would be a BIT less confusing if you wrote it like this (in my opinion), especially if you use sublime text as editor:
1
2
myName = "Yank"
parse("hudtxt2 1 1 \"Your name is "..myName.."\" 320 240 1")
edited 4×, last 08.09.14 09:14:47 pm

old Re: Common Mistakes by Scripter

DC
Admin Off Offline

Quote
Here's a super common mistake. The bad thing about it: You won't even notice that you made a mistake because it works even though it's nonsense:

× Wrong:
1
parse("equip "..id.." "..weapon.."")
The .."" at the end is just pointless. It adds an empty string. There is NO reason to do that.

√ Right:
1
parse("equip "..id.." "..weapon)
or even better: use wrapper.lua to increase the readability of your script.

old Re: Common Mistakes by Scripter

omg
User Off Offline

Quote
saying that you made arrays too big is a pretty ridiculous problem...theres no reason to nitpick about servers having less than 32 players. it's decrease readability for a couple kb of space.

old Re: Common Mistakes by Scripter

_Yank
User Off Offline

Quote
@user omg: Why would it discrease readabilty, pretty much the contrary. And, what if you were debugging or something ? It could confuse you
Also, what if the player data table is HUGE (Like in a complex AI for bots) ?
To the start Previous 1 Next To the start
Log in to reply Scripts overviewCS2D overviewForums overview