• 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 Need explanation on scope and the passing of variables

I

Icy

Guest
Here is a talkaction I quickly wrote up:
Lua:
--@author: Icy
--@date: January 17th, 2011
--@purpose:
--	Provide an example of accessing a pseudo-global variable

-- declare variables
local number

-- function to be called on execution of talkaction
function onSay(cid, words, param, channel)

	if(setVariables(param)) then
		doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, 'Starting...')
		local result = doMath()
	else
		return doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_RED, 'Variables not set.')
	end
	
	return doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, 'The result is: ' .. result)
end

-- multiplies the previously set variable by 3
function doMath()
	
	local ret = number * 3
	
	return ret
end

-- function to set variables
function setVariables(param)
	
	if not(isNumber(param)) then
		return false
	else
		number = tonumber(param)
	
	return true
end

So if this talkaction was executed like this:


It should return the message:

The result is: 15
(the product of 5 * 3)


The thing is.. to access the number that was set as a parameter I have to set it as a "global" variable outside of the onSay function.

My question to you: Is there any way to pass it as a parameter instead?
 
Lua:
--@author: Icy
--@date: January 17th, 2011
--@purpose:
--	Provide an example of accessing a pseudo-global variable
  
-- function to be called on execution of talkaction
function onSay(cid, words, param, channel)
	local num = setVariables(param)
	if(num) then
		doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, 'Starting...')
		local result = doMath(num)
		doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, 'The result is: ' .. result)
	else
		return doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_RED, 'Variables not set.')
	end
 
	return true
end
 
-- multiplies the previously set variable by 3
function doMath(num)
 
	local ret = num * 3
 
	return ret
end
 
-- function to set variables
function setVariables(param)
 
	if not(isNumber(param)) then
		return false
	end
 
	return tonumber(param)
end

Since I never heard of anything like pointers in lua you cannot edit the variable by passing it as parameter
 
Back
Top