Redis+Lua - routing calls by mobile operator DEF code

Case: Fast & Easy search for the mobile operator using the def code.

First, obtain data for the table. In this case, I used the DEF 9XX set of the Russian codes from csv file.

Source file structure:

АВС/ DEF;От;До;Емкость;Оператор;Регион
900;0000000;0061999;62000;ООО "Т2 Мобайл";Краснодарский край
900;0062000;0062999;1000;ООО "Т2 Мобайл";Ростовская обл.
...
With regular expressions, I converted this to the form as I needed:
          http://redis.io      
                _._                                                 
           _.-``__ ''-._                                             
      _.-``    `.  `_.  ''-._ 
  .-`` .-```.  ```\/    _.,_ ''-._                                   
 (    '      ,       .-`  | `,    )
 |`-._`-...-` __...-.``-._|'` _.-'|
 |    `-._   `._    /     _.-'    |
  `-._    `-._  `-./  _.-'    _.-'                                   
 |`-._`-._    `-.__.-'    _.-'_.-'|                                  
 |    `-._`-._        _.-'_.-'    |                 
  `-._    `-._`-.__.-'_.-'    _.-'                                   
 |`-._`-._    `-.__.-'    _.-'_.-'|                                  
 |    `-._`-._        _.-'_.-'    |                                  
  `-._    `-._`-.__.-'_.-'    _.-'                                   
      `-._    `-.__.-'    _.-'                                       
          `-._        _.-'                                           
              `-.__.-'                                 
def;end range with def;"name:start range with def"
900;9000061999;"tele2:9000000000"
900;9000062999;"tele2:9000062000"
...
Second, I imported csv to Redis with help ZADD commands.
cat CSV_FILE.csv | awk -F';' '{print "ZADD",  $1, $2, $3 "\n"}' | redis-cli --pipe
Mass insertion of data is very easy with awk.
You can test the output by running it without a pipe to redis-cli.
Once done, let's use the ZRANGEBYSCORE command to search:
127.0.0.1:6379> ZRANGEBYSCORE 999 9999999998 +inf LIMIT 0 1
Скартел:9999600000
I created this case for use with Freeswitch PBX. FS has mod_hiredis as a Redis backend, but mod_hiredis does not pass ZADD family commands (I could not, may be you). This is not too bad since I am using Lua dialplan. Below is my simple the test script, using the redis-lua client library:
local num = arg[1];
local def = num:sub(2,4);
print("def:" .. def);
local cut8 = num:sub(2,11);
print("cut8:" .. cut8);
 
local redis = require 'redis'
local client = redis.connect('127.0.0.1', 6379)
local pass = client:auth('REDIS_PASS')
local response = client:ping();
local ret = client:zrangebyscore(def,cut8,'+inf',{ limit = {0,1}});
 
local function has_value (tab, val)
    for index, value in ipairs(tab) do
        if value == val then
            return true
        end
    end
    return false
end
 
local ret_sep = ':';
local ret_opsos = ret[1];
local tbl_opsos = {};
 
if (ret_opsos ~= nil) then
                ret_opsos:gsub("([^"..ret_sep.."]*)"..ret_sep, function(c)
                table.insert(tbl_opsos, c);
        end)
else
        table.insert(tbl_opsos,"ERROR")
end
 
local opsos = {'tele2', 'megafon', 'mts', 'beeline'};
 
local exists = has_value(opsos,tbl_opsos[1]);
if ( exists ) then
        print(exists);
else 
        print("Opsos:" .. tbl_opsos[1])
end

Test:

./redis.lua 8999999998
def:999
cut8:999999998
Opsos: Скартел
2020/08/04 · Zvezdo4kin

Vim Commands Cheat Sheet


:q[uit] Quit Vim. This fails when changes have been made.
:q[uit]! Quit without writing.
:cq[uit] Quit always, without writing.
:wq Write the current file and exit.
:wq! Write the current file and exit always.
:wq {file} Write to {file}. Exit if not editing the last
:wq! {file} Write to {file} and exit always.
:[range]wq[!][file] Same as above, but only write the lines in [range].
ZZ Write current file, if modified, and exit.
ZQ Quit current file and exit (same as «:q!»).

:e[dit] Edit the current file. This is useful to re-edit the current file, when it has been changed outside of Vim.
:e[dit]! Edit the current file always. Discard any changes to the current buffer. This is useful if you want to start all over again.
:e[dit] {file} Edit {file}.
:e[dit]! {file}Edit {file} always. Discard any changes to the current buffer.
gf Edit the file whose name is under or after the cursor. Mnemonic: «goto file».

a Append text after the cursor [count] times.
A Append text at the end of the line [count] times.
i Insert text before the cursor [count] times.
I Insert text before the first non-blank in the line [count] times.
gIInsert text in column 1 [count] times.
o Begin a new line below the cursor and insert text, repeat [count] times.
O Begin a new line above the cursor and insert text, repeat [count] times.

:r[ead] [name]Insert the file [name] below the cursor.
:r[ead] !{cmd}Execute {cmd} and insert its standard output below the cursor.

<Del> or
x
Delete [count] characters under and after the cursor
X Delete [count] characters before the cursor
d{motion} Delete text that {motion} moves over
dd Delete [count] lines
D Delete the characters under the cursor until the end of the line
{Visual}x or
{Visual}d
Delete the highlighted text (for {Visual} see Selecting Text).
{Visual}CTRL-H or
{Visual}
When in Select mode: Delete the highlighted text
{Visual}X or
{Visual}D
Delete the highlighted lines
:[range]d[elete] Delete [range] lines (default: current line)
:[range]d[elete] {count} Delete {count} lines, starting with [range]

r{char} replace the character under the cursor with {char}.
R Enter Insert mode, replacing characters rather than inserting
~ Switch case of the character under the cursor and move the cursor to the right. If a [count] is given, do that many characters.
~{motion}switch case of {motion} text.
{Visual}~Switch case of highlighted text

:[range]s[ubstitute]/{pattern}/{string}/[c][e][g][p][r][i][I] [count] For each line in [range] replace a match of {pattern} with {string}.
:[range]s[ubstitute] [c][e][g][r][i][I] [count] :[range]&[c][e][g][r][i][I] [count]Repeat last :substitute with same search pattern and substitute string, but without the same flags. You may add extra flags
The arguments that you can use for the substitute commands:
[c]  Confirm each substitution.  Vim positions the cursor on the matching
  string.  You can type:
      'y'      to substitute this match
      'n'      to skip this match
         to skip this match
      'a'      to substitute this and all remaining matches {not in Vi}
      'q'      to quit substituting {not in Vi}
      CTRL-E  to scroll the screen up {not in Vi}
      CTRL-Y  to scroll the screen down {not in Vi}.
[e]     When the search pattern fails, do not issue an error message and, in
  particular, continue in maps as if no error occurred.  
[g]  Replace all occurrences in the line.  Without this argument,
  replacement occurs only for the first occurrence in each line.
[i]  Ignore case for the pattern.  
[I]  Don't ignore case for the pattern.  
[p]  Print the line containing the last substitute.

«{a-zA-Z0-9.%#:-»} Use register {a-zA-Z0-9.%#:-«} for next delete, yank or put (use uppercase character to append with delete and yank) ({.%#:} only work with put).
:reg[isters] Display the contents of all numbered and named registers.
:reg[isters] {arg} Display the contents of the numbered and named registers that are mentioned in {arg}.
:di[splay] [arg] Same as :registers.
[«x]y{motion} Yank {motion} text [into register x].
[«x]yy Yank [count] lines [into register x]
[«x]Y yank [count] lines [into register x] (synonym for yy).
{Visual}[«x]y Yank the highlighted text [into register x] (for {Visual} see Selecting Text).
{Visual}[«x]Y Yank the highlighted lines [into register x]
:[range]y[ank] [x] Yank [range] lines [into register x].
:[range]y[ank] [x] {count}Yank {count} lines, starting with last line number in [range] (default: current line), [into register x].
[«x]p Put the text [from register x] after the cursor [count] times.
[«x]P Put the text [from register x] before the cursor [count] times.
[«x]gp Just like «p», but leave the cursor just after the new text.
[«x]gP Just like «P», but leave the cursor just after the new text.
:[line]pu[t] [x] Put the text [from register x] after [line] (default current line).
:[line]pu[t]! [x] Put the text [from register x] before [line] (default current line).

u Undo [count] changes.
:u[ndo]Undo one change.
CTRL-R Redo [count] changes which were undone.
:red[o]Redo one change which was undone.
U Undo all latest changes on one line. {Vi: while not moved off of it}
. Repeat last change, with count replaced with [count].

Basic motion commands:

        k              
      h   l          
        j             
h or[count] characters to the left (exclusive).
l or\\or[count] characters to the right (exclusive).

k or
or
CTRL-P

[count] lines upward

j or
or
CTRL-J or
or
CTRL-N

[count] lines downward (linewise).

0

To the first character of the line (exclusive).

<Home>

To the first character of the line (exclusive).

To the first non-blank character of the line

$ or
<End>

To the end of the line and [count - 1] lines downward

g0 or
g<Home>

When lines wrap ('wrap on): To the first character of the screen line (exclusive). Differs from «0» when a line is wider than the screen. When lines don't wrap ('wrap' off): To the leftmost character of the current line that is on the screen. Differs from «0» when the first character of the line is not on the screen.

g^

When lines wrap ('wrap' on): To the first non-blank character of the screen line (exclusive). Differs from «^» when a line is wider than the screen. When lines don't wrap ('wrap' off): To the leftmost non-blank character of the current line that is on the screen. Differs from «^» when the first non-blank character of the line is not on the screen.

g$ or
g<End&gr;

When lines wrap ('wrap' on): To the last character of the screen line and [count - 1] screen lines downward (inclusive). Differs from «$» when a line is wider than the screen. When lines don't wrap ('wrap' off): To the rightmost character of the current line that is visible on the screen. Differs from «$» when the last character of the line is not on the screen or when a count is used.

f{char}

To [count]'th occurrence of {char} to the right. The cursor is placed on {char} (inclusive).

F{char}

To the [count]'th occurrence of {char} to the left. The cursor is placed on {char} (inclusive).

t{char}

Till before [count]'th occurrence of {char} to the right. The cursor is placed on the character left of {char} (inclusive).

T{char}

Till after [count]'th occurrence of {char} to the left. The cursor is placed on the character right of {char} (inclusive).

;

Repeat latest f, t, F or T [count] times.

,

Repeat latest f, t, F or T in opposite direction [count] times.

- <minus>

[count] lines upward, on the first non-blank character (linewise).

+ or
CTRL-M or
<CR>

[count] lines downward, on the first non-blank character (linewise).

_ <underscore>

[count] - 1 lines downward, on the first non-blank character (linewise).

<C-End> or
G

Goto line [count], default last line, on the first non-blank character.

<C-Home> or
gg

Goto line [count], default first line, on the first non-blank character.

<S-Right> or
w

[count] words forward

<C-Right> or
W

[count] WORDS forward

e

Forward to the end of word [count]

E

Forward to the end of WORD [count]

<S-Left> or
b

[count] words backward

<C-Left> or
B

[count] WORDS backward

ge

Backward to the end of word [count]

gE

Backward to the end of WORD [count]

These commands move over words or WORDS.

A word consists of a sequence of letters, digits and underscores, or a sequence of other non-blank characters, separated with white space (spaces, tabs, ). This can be changed with the 'iskeyword' option.

A WORD consists of a sequence of non-blank characters, separated with white space. An empty line is also considered to be a word and a WORD.

( [count] sentences backward
) [count] sentences forward
{ [count] paragraphs backward
} [count] paragraphs forward
]][count] sections forward or to the next '{' in the first column. When used after an operator, then the '}' in the first column.
][[count] sections forward or to the next '}' in the first column
The operators that can be used are:
  ~  switch case
  d  delete
  c  change
  y  yank
  >  shift right 
  <  shift left 
  !  filter through external command 
  =  filter through 'equalprg' option command 
  gq  format lines to 'textwidth' length 
v start Visual mode per character.
V start Visual mode linewise.
<Esc>exit Visual mode without making any changes

CTRL-Z Suspend Vim, like »:stop». Works in Normal and in Visual mode. In Insert and Command-line mode, the CTRL-Z is inserted as a normal character.
:sus[pend][!] or
:st[op][!]
Suspend Vim. If the '!' is not given and 'autowrite' is set, every buffer with changes and a file name is written out. If the '!' is given or 'autowrite' is not set, changed buffers are not written, don't forget to bring Vim back to the foreground later!

2020/03/26

Vim Commands Cheat Sheet


:q[uit] Quit Vim. This fails when changes have been made.
:q[uit]! Quit without writing.
:cq[uit] Quit always, without writing.
:wq Write the current file and exit.
:wq! Write the current file and exit always.
:wq {file} Write to {file}. Exit if not editing the last
:wq! {file} Write to {file} and exit always.
:[range]wq[!][file] Same as above, but only write the lines in [range].
ZZ Write current file, if modified, and exit.
ZQ Quit current file and exit (same as «:q!»).

:e[dit] Edit the current file. This is useful to re-edit the current file, when it has been changed outside of Vim.
:e[dit]! Edit the current file always. Discard any changes to the current buffer. This is useful if you want to start all over again.
:e[dit] {file} Edit {file}.
:e[dit]! {file}Edit {file} always. Discard any changes to the current buffer.
gf Edit the file whose name is under or after the cursor. Mnemonic: «goto file».

a Append text after the cursor [count] times.
A Append text at the end of the line [count] times.
i Insert text before the cursor [count] times.
I Insert text before the first non-blank in the line [count] times.
gIInsert text in column 1 [count] times.
o Begin a new line below the cursor and insert text, repeat [count] times.
O Begin a new line above the cursor and insert text, repeat [count] times.

:r[ead] [name]Insert the file [name] below the cursor.
:r[ead] !{cmd}Execute {cmd} and insert its standard output below the cursor.

<Del> or
x
Delete [count] characters under and after the cursor
X Delete [count] characters before the cursor
d{motion} Delete text that {motion} moves over
dd Delete [count] lines
D Delete the characters under the cursor until the end of the line
{Visual}x or
{Visual}d
Delete the highlighted text (for {Visual} see Selecting Text).
{Visual}CTRL-H or
{Visual}
When in Select mode: Delete the highlighted text
{Visual}X or
{Visual}D
Delete the highlighted lines
:[range]d[elete] Delete [range] lines (default: current line)
:[range]d[elete] {count} Delete {count} lines, starting with [range]

r{char} replace the character under the cursor with {char}.
R Enter Insert mode, replacing characters rather than inserting
~ Switch case of the character under the cursor and move the cursor to the right. If a [count] is given, do that many characters.
~{motion}switch case of {motion} text.
{Visual}~Switch case of highlighted text

:[range]s[ubstitute]/{pattern}/{string}/[c][e][g][p][r][i][I] [count] For each line in [range] replace a match of {pattern} with {string}.
:[range]s[ubstitute] [c][e][g][r][i][I] [count] :[range]&[c][e][g][r][i][I] [count]Repeat last :substitute with same search pattern and substitute string, but without the same flags. You may add extra flags
The arguments that you can use for the substitute commands:
[c]  Confirm each substitution.  Vim positions the cursor on the matching
  string.  You can type:
      'y'      to substitute this match
      'n'      to skip this match
         to skip this match
      'a'      to substitute this and all remaining matches {not in Vi}
      'q'      to quit substituting {not in Vi}
      CTRL-E  to scroll the screen up {not in Vi}
      CTRL-Y  to scroll the screen down {not in Vi}.
[e]     When the search pattern fails, do not issue an error message and, in
  particular, continue in maps as if no error occurred.  
[g]  Replace all occurrences in the line.  Without this argument,
  replacement occurs only for the first occurrence in each line.
[i]  Ignore case for the pattern.  
[I]  Don't ignore case for the pattern.  
[p]  Print the line containing the last substitute.

«{a-zA-Z0-9.%#:-»} Use register {a-zA-Z0-9.%#:-«} for next delete, yank or put (use uppercase character to append with delete and yank) ({.%#:} only work with put).
:reg[isters] Display the contents of all numbered and named registers.
:reg[isters] {arg} Display the contents of the numbered and named registers that are mentioned in {arg}.
:di[splay] [arg] Same as :registers.
[«x]y{motion} Yank {motion} text [into register x].
[«x]yy Yank [count] lines [into register x]
[«x]Y yank [count] lines [into register x] (synonym for yy).
{Visual}[«x]y Yank the highlighted text [into register x] (for {Visual} see Selecting Text).
{Visual}[«x]Y Yank the highlighted lines [into register x]
:[range]y[ank] [x] Yank [range] lines [into register x].
:[range]y[ank] [x] {count}Yank {count} lines, starting with last line number in [range] (default: current line), [into register x].
[«x]p Put the text [from register x] after the cursor [count] times.
[«x]P Put the text [from register x] before the cursor [count] times.
[«x]gp Just like «p», but leave the cursor just after the new text.
[«x]gP Just like «P», but leave the cursor just after the new text.
:[line]pu[t] [x] Put the text [from register x] after [line] (default current line).
:[line]pu[t]! [x] Put the text [from register x] before [line] (default current line).

u Undo [count] changes.
:u[ndo]Undo one change.
CTRL-R Redo [count] changes which were undone.
:red[o]Redo one change which was undone.
U Undo all latest changes on one line. {Vi: while not moved off of it}
. Repeat last change, with count replaced with [count].

Basic motion commands:

        k              
      h   l          
        j             

h or

[count] characters to the left (exclusive).

l or
or

[count] characters to the right (exclusive).

k or
or
CTRL-P

[count] lines upward

j or
or
CTRL-J or
or
CTRL-N

[count] lines downward (linewise).

0

To the first character of the line (exclusive).

<Home>

To the first character of the line (exclusive).

To the first non-blank character of the line

$ or
<End>

To the end of the line and [count - 1] lines downward

g0 or
g<Home>

When lines wrap ('wrap on): To the first character of the screen line (exclusive). Differs from «0» when a line is wider than the screen. When lines don't wrap ('wrap' off): To the leftmost character of the current line that is on the screen. Differs from «0» when the first character of the line is not on the screen.

g^

When lines wrap ('wrap' on): To the first non-blank character of the screen line (exclusive). Differs from «^» when a line is wider than the screen. When lines don't wrap ('wrap' off): To the leftmost non-blank character of the current line that is on the screen. Differs from «^» when the first non-blank character of the line is not on the screen.

g$ or
g<End&gr;

When lines wrap ('wrap' on): To the last character of the screen line and [count - 1] screen lines downward (inclusive). Differs from «$» when a line is wider than the screen. When lines don't wrap ('wrap' off): To the rightmost character of the current line that is visible on the screen. Differs from «$» when the last character of the line is not on the screen or when a count is used.

f{char}

To [count]'th occurrence of {char} to the right. The cursor is placed on {char} (inclusive).

F{char}

To the [count]'th occurrence of {char} to the left. The cursor is placed on {char} (inclusive).

t{char}

Till before [count]'th occurrence of {char} to the right. The cursor is placed on the character left of {char} (inclusive).

T{char}

Till after [count]'th occurrence of {char} to the left. The cursor is placed on the character right of {char} (inclusive).

;

Repeat latest f, t, F or T [count] times.

,

Repeat latest f, t, F or T in opposite direction [count] times.

- <minus>

[count] lines upward, on the first non-blank character (linewise).

+ or
CTRL-M or
<CR>

[count] lines downward, on the first non-blank character (linewise).

_ <underscore>

[count] - 1 lines downward, on the first non-blank character (linewise).

<C-End> or
G

Goto line [count], default last line, on the first non-blank character.

<C-Home> or
gg

Goto line [count], default first line, on the first non-blank character.

<S-Right> or
w

[count] words forward

<C-Right> or
W

[count] WORDS forward

e

Forward to the end of word [count]

E

Forward to the end of WORD [count]

<S-Left> or
b

[count] words backward

<C-Left> or
B

[count] WORDS backward

ge

Backward to the end of word [count]

gE

Backward to the end of WORD [count]

These commands move over words or WORDS.

A word consists of a sequence of letters, digits and underscores, or a sequence of other non-blank characters, separated with white space (spaces, tabs, ). This can be changed with the 'iskeyword' option.

A WORD consists of a sequence of non-blank characters, separated with white space. An empty line is also considered to be a word and a WORD.

( [count] sentences backward
) [count] sentences forward
{ [count] paragraphs backward
} [count] paragraphs forward
]][count] sections forward or to the next '{' in the first column. When used after an operator, then the '}' in the first column.
][[count] sections forward or to the next '}' in the first column
The operators that can be used are:
  ~  switch case
  d  delete
  c  change
  y  yank
  >  shift right 
  <  shift left 
  !  filter through external command 
  =  filter through 'equalprg' option command 
  gq  format lines to 'textwidth' length 
v start Visual mode per character.
V start Visual mode linewise.
<Esc>exit Visual mode without making any changes

CTRL-Z Suspend Vim, like »:stop». Works in Normal and in Visual mode. In Insert and Command-line mode, the CTRL-Z is inserted as a normal character.
:sus[pend][!] or
:st[op][!]
Suspend Vim. If the '!' is not given and 'autowrite' is set, every buffer with changes and a file name is written out. If the '!' is given or 'autowrite' is not set, changed buffers are not written, don't forget to bring Vim back to the foreground later!

Daniel Gryniewicz / dang@fprintf.net

2020/03/26

Sublime Regex

Sublime Text Regular Expression Cheat Sheet

A cheat sheet about regex in Sublime Text.

Special characters

expression Description
. Match any character
^ Match line begin
$ Match line end
* Match previous RE 0 or more times greedily
*? Match previous RE 0 or more times non-greedily
+ Match previous RE 1 or more times greedily
+? Match previous RE 1 or more times non-greedily
? Match previous RE 0 or 1 time greedily
?? Match previous RE 0 or 1 time non-greedily
A|B Match either RE A or B
{m} Match previous RE exactly m times
{m,n} Match previous RE m to n times greedily
{m, n}?Match previous RE m to n times, no-greedily

Character set

expression Description
[abc] Match either a, b or c
[^abc] Match any character not in this set (i.e., not a, b and c)
[a-z] Match the range from a to z
[a-f2-8] Match the range from a to z or the range from 2 to 8
[a\-z] Match a, - or z
[a-] Match a, -
[-a] Match -, a
[-a] Match -, a
[{}*|()[]+\^$.?]Match either one of the chacters in []{}*|()+^$?.
  • Note that you can also use character class inside [], for example, [\w] matches any character in word character class.

Character class

An expression of the form [[:name:]] matches the named character class name.

class name Description
alnum Any alpha-numeric character
alpha Any alphabetic character.
digit Any decimal digit.
xdigitAny hexadecimal digit character.
lower Any lower case character.
upper Any upper case character.
cntrl Any control character1.
print Any printable character.
punct Any punctuation character. 2
space Any whitespace character. 3
word Any word character (alphanumeric characters plus the underscore).

Note: To use upper and lower, you have to enable case sensitve search.

class nameDescription
\dEqual to [[:digit:]]
\lEqual to [[:lower:]]
\uEqual to [[:upper:]]
\sEqual to [[:space:]]
\wEqual to [[:word:]]
\DEqual to [^[:digit:]]
\LEqual to [^[:lower:]]
\UEqual to [^[:upper:]]
\WEqual to [^[:word:]]

Regex groups

expression Description
(?<NAME>pattern)Define a regex group named NAME which you can later refer to with \g{NAME}
(?=pattern) Positive lookahead, consumes zero characters, the preceding RE only matches if this matches
(?!pattern) Negative lookahead, consumes zero characters, the preceding RE only matches if this does not match
(?<=pattern) Positive lookbehind, consumes zero characters, the following RE will only match if preceded with this fixed length RE.
(?<!pattern) Negative lookbehind, consumes zero characters, the following RE will only match if not preceded with this fixed length RE.
expression Description
\1 Refer to first regex group
\g{1} Refer to first regex group
\g{12}Refer to 12th regex group
\g{-1}Refer to last regex group
\g{-2}Refer to last but one regex group
  • The regex groups are indexed by the order of their opening braces.
  • Note the \g{NUM} form allows for matching regex group index larger than 9, for example, \g{12}.

Miscellaneous

class name Description
\xdd A hexadecimal escape sequence - matches the single character whose code point is 0xdd.
\x{dddd}A hexadecimal escape sequence - matches the single character whose code point is 0xdddd.

The following escape sequences match the boundaries of words:

class nameDescription
\<Matches the start of a word.
\>Matches the end of a word.
\bMatches a word boundary (the start or end of a word).
\BMatches only when not at a word boundary.

References

** The title image is taken from here.


  1. Control character explanation: https://en.wikipedia.org/wiki/Control_character ↩︎

  2. There are 14 punctuation marks in English: https://grammar.yourdictionary.com/punctuation/what/fourteen-punctuation-marks.html ↩︎

  3. For whitespace character, see https://en.wikipedia.org/wiki/Whitespace_character ↩︎

2020/03/06 · Oleg Zvezdo4kin · 0 комментариев (-я)

Lua as a Configuration And Data Exchange Language For "C"

config.lua

printers = {
    printer1 = "Foo branch",
    printer2 = "Fek bhanch",
    printer3 = "Fuk branch" 
}
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include "lua5.2/lua.h"
#include "lua5.2/lauxlib.h"
#include "lua5.2/lualib.h"
#define CONFIG_FILE "config.lua"
 
static char * getconf (char *mod, char *key)
{
  char *res;
 
  lua_State *L = luaL_newstate();
  luaL_openlibs(L);
 
  if (luaL_loadfile(L, CONFIG_FILE) || lua_pcall(L, 0, 0, 0))
      {
        fprintf(stderr, "Couldn't load file: %s\n", lua_tostring(L, -1));
      }
 
  lua_getglobal(L, mod);
 
  if(!lua_istable(L, -1))
      {
        fprintf(stderr, "Table type error: %s\n", (lua_tostring(L, -1)) );
      }
 
  lua_getfield(L, -1, key);
 
   if(!lua_isstring(L, -1))
       {
         fprintf(stderr, "String type error: %s\n", (lua_tostring(L, -1)));
       }
  res = strdup((char *)lua_tostring(L, -1));
  lua_pop(L, 1);
  lua_close(L);
  return res;
}
int main(int argc, char **argv)
{
static char *device;
device = getconf("printers", "printer1");
}

https://www.netbsd.org/~mbalmer/lua/lua_config.pdf

2019/11/28 · Oleg Zvezdo4kin · 0 комментариев (-я)

Предыдущие записи >>

  • blog.txt
  • Последние изменения: 2019/03/27