Suggestion to refactor this

General discussion about LÖVE, Lua, game development, puns, and unicorns.
Post Reply
cfazzini
Prole
Posts: 3
Joined: Sat Sep 16, 2017 12:14 pm

Suggestion to refactor this

Post 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)
User avatar
raidho36
Party member
Posts: 2063
Joined: Mon Jun 17, 2013 12:00 pm

Re: Suggestion to refactor this

Post by raidho36 »

Try using a normal class system.
User avatar
ivan
Party member
Posts: 1915
Joined: Fri Mar 07, 2008 1:39 pm
Contact:

Re: Suggestion to refactor this

Post 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).
Post Reply

Who is online

Users browsing this forum: Bing [Bot], Google [Bot] and 4 guests