Page 1 of 1

Suggestion to refactor this

Posted: Mon Sep 18, 2017 2:59 pm
by cfazzini
Is there a better way to refactor this. Ive got the following line:

Code: Select all

player = require('modules/player')('wizard')
In modules/player.lua. I’ve got:

Code: Select all

function health(class)
  if class == 'wizard' then
    return 80

  elseif class == 'warrior' then
    return 100
  end
end

function mana(class)
  if class == 'wizard' then
    return 100

  elseif class == 'warrior' then
    return 80
  end
end

function healthPool(class)
  if class == 'wizard' then
    return 80

  elseif class == 'warrior' then
    return 100
  end
end

function manaPool(class)
  if class == 'wizard' then
    return 100

  elseif class == 'warrior' then
    return 80
  end
end

return function(class)
    speed       = 100,
    x           = 50,
    y           = 50,
    health      = health(class),
    mana        = mana(class),
    health_pool = healthPool(class),
    mana_pool   = manaPool(class)
  }
end
Basically health, mana, health_pool, and mana_pool are attributes dependent on the class type (ie. wizard or warrior)

Re: Suggestion to refactor this

Posted: Mon Sep 18, 2017 4:49 pm
by raidho36
Try using a normal class system.

Re: Suggestion to refactor this

Posted: Mon Sep 18, 2017 5:57 pm
by ivan
I think it's much cleaner to move your definitions outside of the code, so:

Code: Select all

local defs = {
  wizard = { health=80, hpool=80, mana=100, mpool=100, speed = 80 },
  warrior = { health=100, hpool=100, mana=80, mpool=80, speed = 100 },
  -- add more classes here
}
This is important because it separates your static definitions from the rest of your code.

Code: Select all

local defs = require('game.defs')

-- note: no stats/values hard-coded below
local function createCharacter(classname, x,y)
  local t = { x=x, y=y }
  for k,v in pairs(defs[classname]) do
    t[k] = v
  end
  return t
end
Like Raiho said, the next step might be to introduce inheritance (possibly using metatables).