Calculator script

Discuss or post Lua object scripts
Locked
Edwin
Site Admin
Posts: 154
Joined: Mon Apr 09, 2007 10:04 am
Location: Almere, The Netherlands
Contact:

Calculator script

Post by Edwin » Sat Apr 18, 2009 3:00 pm

Image
This is still a bit messy and the API will probably change a lot but here is my calculator script for VP version 0.2.9. It has some limitations but it works most of the time :P

For the display use the following action:

Code: Select all

create name calculator
For each of the buttons set the description to one of the numbers or actions and set the action like this:

Code: Select all

create sign;activate notify calculator
Use this script for the display:

Code: Select all

signvalue = ''
val1 = 0
val2 = 0
action = nil
shouldclear = false
 
function notification(sender, args)
	local str = sender:description()
	local num = tonumber(str)
	if num == nil then
		if str == 'CE' then
			signvalue = ''
			action = nil
			setsign()
 
		elseif str == '*' then
			setvalue()
			action = function() signvalue = val1*val2 end
			shouldclear = true
		elseif str == '/' then
			setvalue()
			action = function() signvalue = val1/val2 end
			shouldclear = true
		elseif str == '-' then
			setvalue()
			action = function() signvalue = val1-val2 end
			shouldclear = true
		elseif str == '+' then
			setvalue()
			action = function() signvalue = val1 + val2 end
			shouldclear = true
		elseif str == '=' then
			setvalue()
			action()
			setsign()
			action = nil
			shouldclear = true
		end
	else
		if shouldclear then
			signvalue = ''
			shouldclear = false
		end
		signvalue = signvalue .. str
		setsign()
	end -- if num == nil
end
 
function setvalue()
	if action == nil then
		val1 = tonumber(signvalue)
	else
		val2 = tonumber(signvalue)
	end
end
 
function setsign()
	this:settexture(SignTexture:new(string.format("%8s",signvalue), 'FFFFFF', '000000'))
end

Xenion
Moderator
Posts: 49
Joined: Sun Apr 15, 2007 7:38 pm
Location: Belgium
Contact:

Re: Calculator script

Post by Xenion » Sat Apr 18, 2009 5:40 pm

I don't get it: the function is declared "function notification(sender, args)", but you call it from VP with "activate notify calculator"?

Edwin
Site Admin
Posts: 154
Joined: Mon Apr 09, 2007 10:04 am
Location: Almere, The Netherlands
Contact:

Re: Calculator script

Post by Edwin » Sat Apr 18, 2009 7:23 pm

Xenion wrote:I don't get it: the function is declared "function notification(sender, args)", but you call it from VP with "activate notify calculator"?
The object containing the script also has "create name calculator", so it sends a notification to the object with the name calculator.

As I said, the API will probably change.

Locked