github.com/coyove/nj@v0.0.0-20221110084952-c7f8db1065c3/tests/string.nj.lua (about)

     1  assert( "abc" == "abc")
     2  -- assert( "abc" == "\97\98\99")
     3  assert( "abc" == "\x61\x62\x63")
     4  local abc = "abc" 
     5  assert( "abc吱吱吱" == abc + "吱吱" + "吱")
     6  assert( "abc吱吱吱" == "abc\u5431\u5431\u5431")
     7  
     8  
     9  local a, b = re([["(\d+)"]]).findall("a\"12\" \"2\"3")
    10  assert(a[0] == [["12"]] and a[1] == "12" and b[0] == [["2"]] and b[1] == "2")
    11  
    12  local err = error("err")
    13  print("reflectLoad: ", err.error())
    14  assert(err.error() == "err")
    15  assert("eerrrr" == re("(e|r)").replace(err.error(), "$1$1"))
    16  
    17  assert("x" == ("嘻x嘻").trim("嘻"))
    18  assert("嘻x" == ("嘻x嘻").trimright("嘻"))
    19  assert("x嘻" == ("嘻x嘻").trimleft("嘻"))
    20  
    21  -- json generator
    22  do
    23  	function str.json_get(p) return json.parse(this)[p] end
    24  	local j = json.stringify({
    25  	      a = 'A',
    26  	      "b-2": true,
    27  	})
    28      assert(j.json_get('a'), 'A')
    29      assert(j.json_get('b-2'), true)
    30  end
    31  
    32  function str.reverse()
    33  	x = ""
    34      tmp = this
    35      while #tmp > 0 do
    36          local r, sz = tmp.decodeutf8()
    37          x = chr(r) + x
    38          tmp = tmp[sz:]
    39      end
    40  	return x
    41  end
    42  assert(("abc")==(("cba").reverse()))
    43  assert(("あbc")==(("cbあ").reverse()))
    44  
    45  function foo(x)
    46  	local a= x.split(",").copy(1, 2,["x","y","z"]) 
    47  	assert(a.istyped())
    48  	return a
    49  end
    50  
    51  function array.equals(rhs)
    52  	if #rhs != #this then return false end
    53  	for i, v in rhs do
    54  		if v != this[i] then return false end
    55  	end
    56  	return true
    57  end
    58  
    59  assert(foo("1,2,3").equals(["1","x","3"]))
    60  
    61  assert(json.parse("null") is nil)
    62  assert(json.parse("true") is true)
    63  assert(json.parse("false") is bool)
    64  assert(json.parse.try("nil") is error)