This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
meeko011's profile picture

Function returns same thing every time.

Started by meeko011, 29 January 2016 - 02:34 AM
meeko011 #1
Posted 29 January 2016 - 03:34 AM
I'm working on a concept for a Minecraft mod where there are alignments and PVP is changed based on alignment. The most math I'm willing to do right now is create an algorithm that calculates how much currency a player of one alignment will get from killing another. Alignment is from 5 to -5. Positive is Good, 0 is Neutral, and negative is Evil. To test this in Lua I'm using a function to compare it to 0 then give 1, 0, or -1 to say whether they're Good, Neutral, or Evil. Then I'm printing the variables, then changing them to absolute value so I don't have to type "math.abs" every time Evil is involved. Looter is the killer and Looted is the dead player.

My problem is that the function for calculating your general alignment returns a 0 every time.

A somewhat related question, wouldn't it be easier for functions if the variable inside the parantheses was an arguments table like tARGS was? If it's possible, is there a way to do that?

Sorry for the cringey coding, I have ADHD and kind of suck at everything. I just noticed I probably could've put a tonumber() around the { .. } or something to avoid typing it three times.


tARGS = { ... }

-- print("tARGS 1 is"..tARGS[1]..".")
-- print("tARGS 2 is"..tARGS[2]..".")

b = tonumber(tARGS[1]) -- Base
o = tonumber(tARGS[2]) -- Looter number
x = tonumber(tARGS[3]) -- Looted number
m = 0 -- Multipler
ad = 0 -- Difference between alignment
oal = 0 -- Looter alignment
xal = 0 -- Looted alignment

if x > o then
  ad = x - o
else
  ad = o - x
end

function align(num, align)
  if num > 0 then
	align = 1
  else
	if num < 0 then
	  align = -1
	else
	  align = 0
	end
  end
end

align(o, oal)
align(x, xal)

print("Alignment difference = "..ad)
print("Looter alignment = "..oal)
print("Looted alignment = "..xal)

math.abs(x)
math.abs(o)

if xal == -1 then
  m = (0.1 * x) + m
end

if xal == 1 then
  m = (-0.05 * x) + m
end
Edited on 29 January 2016 - 02:36 AM
KingofGamesYami #2
Posted 29 January 2016 - 04:15 AM
You can't pass variable variable names. When you do

align = 0

You aren't setting cal or xal to 0, you're setting a variable named align.

Try using return instead,


function align( num )
  if num > 0 then
        return 1
  elseif num < 0 then --#elseif does the same thing your nested if statement does, but looks better
        return -1
  else
        return 0
  end
end

cal = align( o )
Edited on 29 January 2016 - 03:17 AM
Bomb Bloke #3
Posted 29 January 2016 - 11:30 AM
A somewhat related question, wouldn't it be easier for functions if the variable inside the parantheses was an arguments table like tARGS was? If it's possible, is there a way to do that?

There are a couple of ways you can do that; see here for some details.