> but did not want to use inheritance and methods because it needs heap 
> allocation

You are using strings so your objects are doing heap allocations anyway. You 
should replace the strings with IDs of the target which got hit / died if you 
don't want any heap allocation.

You can of course do something similar to dynamic dispatching without 
polymorphism:
    
    
    type MessageType = enum msgHit, msgDeath, msgDayNight
    
    type Message* = object
        textImpl: proc(m: Message): string
        case messageType*: MessageType
        of msgHit:
            target*: string
            hp*: int
        of msgDeath:
            died*: string
        of msgDayNight:
            isDay*: bool
    
    proc hit*(target: string, hp: int): Message =
        Message(messageType: msgHit, target: target, hp: hp,
                textImpl: proc(m: Message): string =
            "You hit " & m.target & " for " & $m.hp & " HP."
        )
    
    proc death*(died: string): Message =
        Message(messageType: msgDeath, died: died,
                textImpl: proc(m: Message): string =
            m.died & " just died."
        )
    
    proc dayNight*(isDay: bool): Message =
        Message(messageType: msgDayNight, isDay: isDay,
                textImpl: proc(m: Message): string =
            if m.isDay: result = "The day has just begun."
            else: result = "Beware! Night is coming."
        )
    
    proc getText*(m: Message): string = m.textImpl(m)
    

Reply via email to