• There is NO official Otland's Discord server and NO official Otland's server list. The Otland's Staff does not manage any Discord server or server list. Moderators or administrator of any Discord server or server lists have NO connection to the Otland's Staff. Do not get scammed!

Lua Questions about (semi-adv?) Lua Scripting.

Guitar Freak

_LüA_n☺b_
Joined
Dec 27, 2008
Messages
831
Reaction score
13
Location
Caracas, Venezuela
Hello there, it's been a while since I last posted a request, and this time I will request something different: Theory :thumbup:

*First fo all, sorry if this is the wrong subforum, mods feel free to move it respectively*

I want some pr0s to explain me some specific things about Lua Scripting that Im having trouble with. And Id like to improve by having some knowledge about them.

There are several questions so if you know only one of them dont worry, post it, Ill +Rep any helpful answers, even if they are questions already answered and you have a correction or a helpful extension.

So here they are, enjoy the never-ending question-encyclopedia of doom :thumbup::

--------
-----------
-------------​


1.- About "for" in general:

1.- Questions about "for" in general.

2.- About "for i = x,x".​

2.- Questions about "for i = x,x".

3.- About "in pairs".

3.- Questions about "in pairs".

4.- About "return".​

4.- Questions about "return".

5.- About "symbols" in general.​

5.- About "symbols" in general.

6.- About "locals and tables".​

6.- About "locals and tables".

7.- About "talkactions".​

7.- About "talkactions".

8.- About "General & Random stuff".​

8.- About "General & Random stuff".

Final Note: Be aware that, in the links, the questions that are numbered in red color (example: 1.1) and/or have a (Solved) at the end of them, is (therefore) because they are solved, but as said on the beginning of this post, you can still post corrections or extensions to them if you want.

-------------
-----------
---------​

Ill post more if I remember more.

I placed the questions in links so you can just look for the big titles in blue to see if you find a category where you can start to answer to keep the post shorter and easier to read (thanks Fare for the idea).

Notice Im not hoping to get them all answered right away, or ever, because they are many (and more to come probably) but it took me a while to write these questions down as detailed as possible for a better comprehension (like 2 hours, didnt think I had so many when I started ^_^), hopefully they will be easy for you to read and answer, and I and others will be able to learn eventually.

And again, if you know just 1 answer, post it! Its generally better than nothing ^_^

Ill +Rep helpful comments. However, Im aware that 6 rep power may not be enough for the possible time you could take to answer a couple of questions, so if its not enough, please do it just for the help of it :)

(Take in consideration that yes, Ive researched for them in Google and learned from some sites aswell but I decided Id rather get some explanations here with TFS-related examples to understand better about it. I also used examples from scripts of this forum for my questions)

Also Im sure other people might be wondering some of the questions here mentioned and it could help them too. That means Ill edit the question-posts with the respective answers (and answerers) as soon as I get them so others can learn too.

Thanks a lot in advance.
-Guitar Freak.
 
Last edited:
PHP:
for i = 1,20 do
    doAddContainerItem(bp, types, count)
end

It simplifies what you want to do,
like add 20 runes to a backpack...
Instead of writing 1 by 1, you write that.

Lua:
local foods =
{
    ham = xxxx,
    meat = xxxx
}

This is like catagorizing something in one area...
The best way to script is SIMPLIFY or SHORTEN everything.

Instead of writing:
Lua:
local ham = xxxx
local meat = xxxx
and so on.

Also:
If you can write a script with 10 lines,
that does the same with a script that is 50 lines,
I would rather write 10 lines.
 
Last edited:
Thanks JDB, +Repped you of course. If you find some more stuff later on the list that you know about, you can post it anytime if you dont have time now, no rush ofc :)

A few doubts about your post:

Lua:
local foods =
{
    ham = xxxx,
    meat = xxxx
}

This is like catagorizing something in one area...
The best way to script is SIMPLIFY or SHORTEN everything.

And to call them then Id have to write for example foods.ham right? Or ham.foods?

And is that what people call a "table" or a table is something else?

And in:

PHP:
for i = 1,20 do
    doAddContainerItem(bp, types, count)
end

It simplifies what you want to do,
like add 20 runes to a backpack...
Instead of writing 1 by 1, you write that.

Can you make another example :p Didnt quite understood that one.

But still thanks for the fast response :thumbup:
 
A table is an array that is able to store more than one value.

Lua:
--This is a table
example = {x, y}

--This is not a table
example = 5

To get a value from a table, we use this:
Lua:
table = {

        thing = 1,
        thigh = 2
}

if table.thigh == 2 then --tables name always comes first
--code
end

Here's an example of a for loop:
Lua:
for i = 1, 3 do
print(i)
end

This will give us the following in the console:
Code:
1
2
3
 
Thanks koko~ :D Thats as clear as Im looking answers to be, thanks again.
+Repped and grats on 3 barz :thumbup:

Edit: Btw forgot bout something quick concerning tables:

Lets say I have this table:
Lua:
food = {

        ham = 1,
        meat = 2
}

If I did for example:

Lua:
namestable = {

        bob = 1,
        john = 2
}

if getCreatureName(cid) ~= namestable then
	do something
end

That "namestable" would take all the values together? Like then that script would "do something" if the creature isnt named bob nor john?
 
Last edited:
That would not work. To do what you want, we use isInArray() :)

Here's an example:
Lua:
namestable = {

        bob = 1,
        john = 2
}

if isInArray(namestable, getCreatureName(cid)) then
  print("The creatures name is " .. namestable[1] .. " or " .. namestable[2])
        else
  print("False")
end

If the players name is bob or john, it will give us this:
Code:
The creatures name is bob or john
 
That would not work. To do what you want, we use isInArray() :)

Here's an example:
Lua:
namestable = {

        bob = 1,
        john = 2
}

if isInArray(namestable, getCreatureName(cid)) then
  print("The creatures name is " .. namestable[1] .. " or " .. namestable[2])
        else
  print("False")
end

If the players name is bob or john, it will give us this:
Code:
The creatures name is bob or john

So this would work aswell:

Lua:
namestable = {

        bob = 1,
        john = 2
}

if not(isInArray(namestable, getCreatureName(cid))) then
  print("The creatures name is not in the array")
end

?
 
So this would work aswell:

Lua:
namestable = {

        bob = 1,
        john = 2
}

if not(isInArray(namestable, getCreatureName(cid))) then
  print("The creatures name is not in the array")
end

?

Yes, it would. :thumbup:

Also, about the string.explode(), here's an example:
Lua:
function onSay(cid, words, param, channel)

--splitted string will contain an array that has 2 strings. If the param was 'hello world', splitted_string[1] will contain "hello" and splitted_string[2] will contain "world"
splitted_string = string.explode(param, " ")

--This will give the player a message that says 'hello world'(in case the param was 'hello world')
rebuilt_param = splitted_string[1] .. " " .. splitted_string[2]
doPlayerSendTextMessage(cid, 22, rebuilt_param)

Sorry for the crappy example that first splits the param and then puts it back like it was again. I hope you get how it can be used. :p
 
Last edited:
4.1- What (in theory) does it do to return TRUE, FALSE, LUA_ERROR and LUA_NO_ERROR?

You use them to check if a function "worked".

Example:
Lua:
function example(apple)
       if apple == 1 then
           return TRUE
        else
           return FALSE
   end
end

Lua:
if example(1) then --This will make it execute what is inside this 'if', since the script returned TRUE or 1.
end

______________________________________

Q: What exactly is cid?

A: 'cid' stands for 'creatureID'.

________________________________________

Q: What is the best way to make randomizations or what are the possible ways?

A: To select a random value, use this:
Lua:
math.random(0, 10) --min_value, max_value

In case the random thing you want is not a number, put the possible values in an array. Then, use this:
Lua:
name_of_array = {"a", "b", "c"}

print(name_of_array[math.random(1, #name_of_array)]) --The #name_of_array returns the size of our array. In this case, 3.

This will give us either 'a', 'b', or 'c' in the console.

_____________________________________________

Q: Is it too different from scripting LUA for OT than scripting for anything else? Only functions change or something else aswell?

A: At the moment, scripting in .LUA for OTServ is function orientated. If the "something else" is also function orientated, only the functions will change. However, OTServ will soon be changing to object orientated scripting.

______________________________________________

Q: How long have you been LUA scripting and how did you learn? *Answer this question only if you answered at least 1 of the other questions, and its optional of course, just out of curiosity*

A: I'm not sure, really! It's been more than 2 years atleast. Though, .LUA scripting isn't really difficult. If you have basic math knowledge, you'll learn it fast ;)
 
Last edited:
Thanks a lot again Koko~, I appreciate it and those about the randomizations is just what I needed for a script Im testing out.

Btw only a doubt about the string.explode part. When you say "lets suppose the param is 'hello world'", that param would be the "words" in talkaction.xml or how do you define that param? or more like if the talkaction is for example /makefood "ham, then ham would be that param?

Ill add your solutions to the main post and:

usefull link: lua-users wiki: Tutorial Directory
btw, your post if very huge, hard to explain anything... + I have no idea whats already explained :) will be much better to have smaller questions in next posts xD

Yep its true but well I just didnt wanted it to look like Im trying to spam :p But maybe its better that way, otherwise the post is just too big and people might not even bother to read through it.. and thanks for the website :) Id seen it already but never got to that tutorial directory part. +Reppek to you too.

In the next posts will be the questions again but one post per "category".
 
Last edited:
--------
-----------
-------------​


1.- About "for" in general:


1.1- Whats the difference between "for xx do" and "if xx then"? (Solved)

Solution by kokokoko:

A 'for' is a loop, we do something x amount of times. An 'if' is used to compare 2 values.

Lua:
for i = 1, 5 do
      do something
   end

Lua:
if i == 1 then
     do something
     else
      do something else
   end

1.2- Why use it and when is it better or more convenient to use "for" instead of "if"? (Solved)

Solution:

Since they have a different functionality, reading their description above on the solution to 1.1 is enough to know why and when to use them.

-------------
-----------
---------​

Both solved on this category, if you have corrections/extensions I dont mind them posted too. I might aswell post new questions in this category if I eventually get them.
 
Last edited:
The param is what you write after the 'talkaction'. So, if we have specified "/makefood" as a talkaction, "ham would be the param.
 
---------
-----------
-------------​

2.- About "for i = x,x".​

2.1- What is it for? (Solved)

Solution by kokokoko:

Complementing the answer from question 1.1, "for i = x,x" is used to make loops. Here's an example of a for loop:
Lua:
for i = 1, 3 do
print(i)
end

Doing that will give us the following in the console:
Code:
1
2
3

Which means it will get all the *natural* numbers of the loop starting from 1 and finishing in 3 (being them 1,2 and 3) and print them in console.

2.2- How does it work? (Solved)

Solution:

Read the solution of question 2.1 above.

2.3- Whats the difference between using it with numbers and using it with letters?

Example of this:
(Taken from Darad's Forever Aol script)

Lua:
function doPlayerRemoveAllConditions(cid)
    for i = 1, 45 do
        if getCreatureCondition(cid, i) == true then
            doRemoveCondition(cid, i)
        end
    end
    doRemoveConditions(cid)
end

Thats with numbers. This is with words:
(Taken from Wlj's Tp Effects script)

Lua:
function onThink(cid, interval, lastExecution)
	for text, pos in pairs(config.positions) do
		doSendMagicEffect(pos, config.effects[math.random(1, #config.effects)])
		doSendAnimatedText(pos, text, config.colors[math.random(1, #config.colors)])
	end
	return LUA_NO_ERROR
end

What would each do? Considering on the second one (and all others I found) there's no "i =", that means with words it cant have it? Or it can? That leads to question 2.5 aswell.

2.4- Ive seen them both mixed (words and numbers), like "for i = 1,getContainerSize(corpse.uid) do", how does that work?

2.5- Whats the difference between "for i = x,x" and "for x,x" (no i =)?

2.6- What does the symbol _ mean in this "system"? I mean when its used like this: for _, x?

Example of this:
Use same example as question 3.2.

-------------
-----------
---------​
 
Last edited:
1.1- Whats the difference between "for xx do" and "if xx then"?

A 'for' is a loop, we do something x amount of times. An 'if' is used to compare 2 values.

Lua:
for i = 1, 5 do
      do something
   end

Lua:
if i == 1 then
     do something
     else
      do something else
   end

1.2- Why use it and when is it better or more convenient to use "for" instead of "if"?

The answer to 1.2 should explain it :thumbup:
 
---------
-----------
-------------​

3.- About "in pairs".

3.1- What does it mean or what is it for?

3.2- Is it only usable when using "for xx do" or can be used with if?

Example of these:
(taken from Slawkens's "Buy items with frags" script)

Lua:
local function getRewardByName(name)
	local tmp = name:lower()
	local tmp2 = ""
	for _, reward in pairs(fragRewards) do
		tmp2 = getItemNameById(reward.itemid)
		if(tmp == tmp2) then
			reward.name = tmp2
			return reward
		end
	end

	return FALSE
end

Explain a bit what the in pairs thing does there.

3.3- If possible, explain the whole "for_, reward in pairs(fragRewards) do" part (supposing the _ thing has been explained on question 2.6).

3.4- Whats the difference between "in pairs" and "in ipairs"?

-------------
-----------
---------​
 
Last edited:
---------
-----------
-------------​

4.- About "return".​

4.1- What (in theory) does it do to return TRUE, FALSE, LUA_ERROR and LUA_NO_ERROR? (Solved)


Solution by kokokoko:

You use them to check if a function "worked".

Example:
Lua:
function example(apple)
       if apple == 1 then
           return TRUE
        else
           return FALSE
   end
end

Lua:
if example(1) then --This will make it execute what is inside this 'if', since the script returned TRUE or 1.
end

4.2- Whats the difference between for example FALSE and LUA_ERROR?

4.3- What else can be "returned" and under what circumstances?


Example of this:
(taken from Slawkens's "Buy items with frags" script)

Does this:
Lua:
function doPlayerAddFrags(cid, amount)
	return doPlayerSetRedSkullTicks(cid, getPlayerRedSkullTicks(cid) + getConfigInfo('timeToDecreaseFrags') * amount)
end

Equal this?

Lua:
function doPlayerAddFrags(cid, amount)
	doPlayerSetRedSkullTicks(cid, getPlayerRedSkullTicks(cid) + getConfigInfo('timeToDecreaseFrags') * amount)
return TRUE
end

Or is it different? If its the same, then returning this way is only for "shortening" purposes?

4.4- Do you need to "return" something when using "for xx do"? If so, what can be returned?

4.5- What happens (in theory/practice) if you dont return anything?


4.6- Are capital letters important when returning stuff? For example is TRUE = true and FALSE = false?


-------------
-----------
---------​
 
Last edited:
---------
-----------
-------------​

5.- About "symbols" in general.​

5.1- Is there a general use for symbols like #, !, ., .., ", ', /, \, :, (, ), [, ], {, }, etc.? Or it depends on the script? If any of them has a general meaning, what is it and which one?

5.2- What does it mean when parenthesys are empty like this: ()? Same as {}, etc.



-------------
-----------
---------​
 
Last edited:
---------
-----------
-------------​

6.- About "locals and tables".​

6.1- Does locals always have to be defined by the word "local" or they can just be written? For example "crystal = 2160" instead of "local crystal = 2160"? If not, whats the difference?

6.2- If I define a local outside a function, lets say at the beginning of the script, does that local work for all the functions in the script? Or only if I define it inside it?

6.3- A "global" is some kind of local? What is it anyway?

6.4- What exactly is a table? How is it written and does it have something to do with locals? (Solved)

Solution by kokokoko:

A table is an array that is able to store more than one value. Those values are the same thing as the "locals" mentioned, but in these arrays, they will be better organized.

Lua:
--This is a table
example = {x, y}

--This is not a table
example = 5

To get a value from a table, we use this:
Lua:
table = {

        thing = 1,
        thigh = 2
}

if table.thigh == 2 then --tables name always comes first
--code
end

6.4.1- I mean Ive always thought tables are just locals but in "groups", like this: (Solved)

Lua:
local example = 
{
	2148,
	2152,
	2160,
}

Am I mistaken?

Solution:

Not mistaken, they are pretty much that. Read solution to question 6.4.

6.5- What kind of symbols can be inside a table and how to use them properly? (Supposing a table is what I mentioned on question 6.4, if not, then apply this same question just supposing it is)

Example of this:
(Taken from JDB's Kill Monster Create TP script)

Lua:
local monsters =
{
    ["Demon"] = {telePos = {x=100, y=100, z=7, stackpos=1}, newPos = {x=100, y=100, z=7}},
    ["Orshabaal"] = {telePos = {x=100, y=100, z=7, stackpos=1}, newPos = {x=100, y=100, z=7}},
    ["Morgaroth"] = {telePos = {x=100, y=100, z=7, stackpos=1}, newPos = {x=100, y=100, z=7}}
}

Like what would happen if I place ("Demon") instead of ["Demon"]? Or [telePos] instead of {telePos}?

6.6- What does this mean/do:

Lua:
                for i = 1, table.maxn() do




-------------
-----------
---------​
 
Last edited:
Back
Top