Pastey An example of a structure using pseudo memory with type checking
- Posted by xecronix
Sep 02, 2015
#!/usr/bin/env eui
-- dude_pseudo.ex
namespace dude
include std/eumem.e
--
-- this is our dude structure (let's hide the implementation details)
--
enum
__TYPE__, -- must be first value in enum
DUDE_AGE,
DUDE_FNAME,
DUDE_LNAME,
__MYSIZE__ -- must be last value in enum
--
-- ID pattern is SOME_NAME_THAT_MAKES_SENSE DOLLAR_SYMBOL SOME_RANDOM_CHARS
--
constant
DUDE_ID = "DUDE$TUJYRHGDESFWA#@$%^"
-- Awesome Euphoria Feature! Let's define what a dude looks like.
type Dude (atom ptr)
return equal(eumem:ram_space[ptr][__TYPE__], DUDE_ID)
end type
-- Magic here is we can add remove "Properties" from our data struct
-- without needing remember to update this.
public constant
SIZEOF_DUDE = __MYSIZE__
--
-- create a new dude object
--
public function new( sequence fname, sequence lname, atom age )
atom ptr = eumem:malloc( SIZEOF_DUDE )
eumem:ram_space[ptr][__TYPE__] = DUDE_ID
eumem:ram_space[ptr][DUDE_AGE] = age
eumem:ram_space[ptr][DUDE_FNAME] = fname
eumem:ram_space[ptr][DUDE_LNAME] = lname
return ptr
end function
--
-- get a dude's age property
--
public function get_age( Dude ptr ) -- Not any old structure will do. We'll make it's a dude!
return eumem:ram_space[ptr][DUDE_AGE]
end function
--
-- set a dude's age property
--
public procedure set_age( Dude ptr, atom age )
eumem:ram_space[ptr][DUDE_AGE] = age
end procedure
--
-- get a dude's fname property
--
public function get_fname( Dude ptr )
return eumem:ram_space[ptr][DUDE_FNAME]
end function
--
-- set a dude's fname property
--
public procedure set_fname( Dude ptr, sequence fname )
eumem:ram_space[ptr][DUDE_FNAME] = fname
end procedure
--
-- get a dude's lname property
--
public function get_lname( Dude ptr )
return eumem:ram_space[ptr][DUDE_LNAME]
end function
--
-- set a dude's lname property
--
public procedure set_lname( Dude ptr, sequence lname )
eumem:ram_space[ptr][DUDE_LNAME] = lname
end procedure
include std/console.e
procedure main()
atom my_dude = dude:new( "John", "Smith", 32 )
display( "[] [] is []", {
get_fname( my_dude ),
get_lname( my_dude ),
get_age( my_dude )
} )
maybe_any_key()
end procedure
main()