Поки що всі наші сценарії робили щось під час запуску. Це має обмежену користь і не дозволяє нам реагувати на реальні дії користувача. Щоб зробити більш просунуті речі, нам потрібно зареєструвати функцію, яка буде викликана при настанні певної події. Найпоширеніша подія, на яку слід реагувати, – це клавіатурний прискорювач.
Now start Ansel, go to “preferences > shortcuts > lua > A shortcut that prints its parameters”, assign a shortcut and try it. You should see a nice message printed on the screen.
Let’s look at the code in detail. We first define a function that takes two strings as input parameters. The first one is the type of event triggered (“shortcut”) and the second is the name of the shortcut (“A shortcut that prints its parameters”). The function itself calls Ansel.print
, which will print the message as an overlay in the main window.
Once that function is defined, we register it as a shortcut callback. To do that we call Ansel.register_event
which is a generic function for all types of events. We tell it that we are registering a shortcut event, then we give the callback to call and finally, we give the string to use to describe the shortcut in the preferences window.
Давайте спробуємо прискорювач, який є трохи більш інтерактивним. Він перегляне зображення, в яких користувач зараз зацікавлений (вибрані або під вказівником миші), і збільшить їх рейтинг:
На даний момент більшість цього коду має бути зрозумілою. Лише пару приміток:
Instead of declaring a function and referencing it, we declare it directly in the call to
Ansel.register_event
this is strictly equivalent but slightly more compact.image.rating
is a field that gives the star rating of any image (between 0 and 5 stars, -1 means rejected).Ansel.gui.action_images
is a table containing all the images of interest. Ansel will act on selected images if any image is selected, and on the image under the mouse if no image is selected. This function makes it easy to follow Ansel’s UI logic in lua.
If you select an image and press your shortcut a couple of times, it will work correctly at first but when you have reached five stars, Ansel will start showing the following error on the console:
Це спосіб Lua повідомляти про помилки. Ми намагалися встановити для зображення оцінку 6, але оцінка може сягати лише 5. Додати перевірку було б тривіально, але давайте підемо складним шляхом і натомість виявимо помилку:
1Ansel.register_event("shortcut",function(event,shortcut)
2 local images = Ansel.gui.action_images
3 for _,v in pairs(images) do
4 result,message = pcall(function()
5 v.rating = v.rating + 1
6 end)
7 if not result then
8 Ansel.print_error("could not increase rating of image "..
9 tostring(v).." : "..message)
10 end
11 end
12end,"Increase the rating of an image")
pcall
запустить свій перший аргумент і вловить будь-який виняток, викликаний ним. Якщо немає винятку, він поверне true
плюс будь-який результат, повернутий функцією. Якщо є виняток, він поверне “false” та повідомлення про помилку винятку. Ми просто перевіряємо ці результати та друкуємо їх на консолі.