rpl.rb/lib/core/string.rb

84 lines
2.3 KiB
Ruby
Raw Normal View History

2021-12-07 16:09:17 +01:00
# frozen_string_literal: true
module Rpl
2021-12-07 15:50:58 +01:00
module Lang
module Core
module_function
2021-12-07 15:50:58 +01:00
# convert an object into a string
def to_string( stack, dictionary )
2021-12-07 15:50:58 +01:00
stack, args = Rpl::Lang::Core.stack_extract( stack, [:any] )
2021-12-07 15:50:58 +01:00
stack << { type: :string,
value: args[0][:value].to_s }
[stack, dictionary]
2021-12-07 15:50:58 +01:00
end
2021-12-07 15:50:58 +01:00
# convert a string into an object
def from_string( stack, dictionary )
2021-12-07 15:50:58 +01:00
stack, args = Rpl::Lang::Core.stack_extract( stack, [%i[string]] )
2021-11-24 15:04:56 +01:00
2021-12-07 15:50:58 +01:00
parsed_input = Rpl::Lang::Parser.new.parse_input( args[0][:value] )
2021-11-24 15:04:56 +01:00
stack += parsed_input
[stack, dictionary]
2021-12-07 15:50:58 +01:00
end
2021-11-24 15:04:56 +01:00
2021-12-07 15:50:58 +01:00
# convert ASCII character code in stack level 1 into a string
def chr( stack, dictionary )
2021-12-07 15:50:58 +01:00
stack, args = Rpl::Lang::Core.stack_extract( stack, [%i[numeric]] )
2021-11-24 15:04:56 +01:00
2021-12-07 15:50:58 +01:00
stack << { type: :string,
value: args[0][:value].chr }
[stack, dictionary]
2021-12-07 15:50:58 +01:00
end
2021-11-24 15:04:56 +01:00
2021-12-07 15:50:58 +01:00
# return ASCII code of the first character of the string in stack level 1 as a real number
def num( stack, dictionary )
2021-12-07 15:50:58 +01:00
stack, args = Rpl::Lang::Core.stack_extract( stack, [%i[string]] )
2021-11-24 15:04:56 +01:00
2021-12-07 15:50:58 +01:00
stack << { type: :numeric,
base: 10,
value: args[0][:value].ord }
[stack, dictionary]
2021-12-07 15:50:58 +01:00
end
2021-11-24 15:04:56 +01:00
2021-12-07 15:50:58 +01:00
# return the length of the string
def size( stack, dictionary )
2021-12-07 15:50:58 +01:00
stack, args = Rpl::Lang::Core.stack_extract( stack, [%i[string]] )
2021-12-07 15:50:58 +01:00
stack << { type: :numeric,
base: 10,
value: args[0][:value].length }
[stack, dictionary]
2021-12-07 15:50:58 +01:00
end
2021-12-07 15:50:58 +01:00
# search for the string in level 1 within the string in level 2
def pos( stack, dictionary )
2021-12-07 15:50:58 +01:00
stack, args = Rpl::Lang::Core.stack_extract( stack, [%i[string], %i[string]] )
2021-11-24 15:04:56 +01:00
2021-12-07 15:50:58 +01:00
stack << { type: :numeric,
base: 10,
value: args[1][:value].index( args[0][:value] ) }
[stack, dictionary]
2021-12-07 15:50:58 +01:00
end
2021-11-24 15:04:56 +01:00
2021-12-07 15:50:58 +01:00
# return a substring of the string in level 3
def sub( stack, dictionary )
2021-12-07 15:50:58 +01:00
stack, args = Rpl::Lang::Core.stack_extract( stack, [%i[numeric], %i[numeric], %i[string]] )
2021-12-07 15:50:58 +01:00
stack << { type: :string,
value: args[2][:value][args[1][:value]..args[0][:value]] }
[stack, dictionary]
2021-12-07 15:50:58 +01:00
end
end
end
end